近期SQL笔记
一些SQL查询语句记录
1.分页查询
sql
SELECT * FROM tbl_note LIMIT 10 OFFSET 20
2.查询总条数
sql
SELECT COUNT(*) FROM tbl_note;
3.多表视图
sql
SELECT note.id,
note.title,
note.description,
note.url,
note.createat,
ct.name AS category,
array_agg(tag.name) AS tags
FROM tbl_notes note,
tbl_tags tag,
tbl_note_tag nt,
tbl_categories ct
WHERE note.id = nt.noteid AND tag.id = nt.tagid AND note.categoryid = ct.id
GROUP BY note.id, note.title, note.description, note.url, ct.name;
4.模糊查询
sql
SELECT * FROM tbl_note WHERE title LIKE '%测试标题%';
5.排序查询
sql
SELECT * FROM tbl_note ORDER BY createat DESC;
补:插入多个表数据的函数
typescript
CREATE OR REPLACE FUNCTION "public"."add_note"("param_title" varchar, "param_description" text, "param_url" varchar, "param_categoryid" varchar, "tags" _varchar)
RETURNS TABLE("result" bool, "msg" text) AS $BODY$BEGIN
-- Routine body goes here...
DECLARE
new_noteid VARCHAR;
new_tagid VARCHAR;
BEGIN
INSERT INTO tbl_notes (title,description,url,categoryid) VALUES (param_title,param_description,param_url,param_categoryid) RETURNING id INTO new_noteid;
FOR i IN 1..array_length(tags, 1) LOOP
INSERT INTO tbl_tags(name) VALUES (tags[i]) ON CONFLICT (name) DO NOTHING RETURNING id INTO new_tagid;
IF NOT FOUND THEN
SELECT id INTO new_tagid
FROM tbl_tags
WHERE name = tags[i];
END IF;
INSERT INTO tbl_note_tag (noteid,tagid) VALUES (new_noteid,new_tagid);
END LOOP;
RETURN QUERY SELECT TRUE as result,'add note success' as msg;
EXCEPTION
WHEN OTHERS THEN
PERFORM write_log('add_note','Excepted error:'||SQLERRM);
RETURN QUERY SELECT FALSE as result, 'Excepted error:'||SQLERRM;
END;
END$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000