我有sqlite3数据库,其中包含示例结构和数据:
CREATE TABLE person(id INTEGER PRIMARY KEY NOT NULL, name STRING NOT NULL);
INSERT INTO "person" VALUES(1,'Jack');
INSERT INTO "person" VALUES(2,'Daniel');
INSERT INTO "person" VALUES(3,'Sam');
INSERT INTO "person" VALUES(4,'T`lc');
CREATE TABLE vote(person_id INTEGER NOT NULL, article_id NUMBER NOT NULL, FOREIGN KEY(person_id) REFERENCES person(id));
INSERT INTO "vote" VALUES(1,43256);
INSERT INTO "vote" VALUES(1,43436);
INSERT INTO "vote" VALUES(1,67388);
INSERT INTO "vote" VALUES(1,43678);
INSERT INTO "vote" VALUES(2,678);
INSERT INTO "vote" VALUES(2,6788);
INSERT INTO "vote" VALUES(2,67388);
INSERT INTO "vote" VALUES(4,67388);
INSERT INTO "vote" VALUES(4,67658);
现在我想(在一个选择查询中)找到所有人的女巫:
我不知道如何做到这一点:/
帮助:'(
答案 0 :(得分:1)
使用OR:
SELECT p.*
FROM PERSON p
WHERE NOT EXISTS(SELECT NULL
FROM VOTE v
WHERE v.person_id = p.id) -- no votes at all
OR NOT EXISTS(SELECT NULL
FROM VOTE v
WHERE v.person_id = p.id
AND v.article_id = 67388)
使用UNION
SELECT p.*
FROM PERSON p
WHERE NOT EXISTS(SELECT NULL
FROM VOTE v
WHERE v.person_id = p.id)
UNION
SELECT p.*
FROM PERSON p
WHERE NOT EXISTS(SELECT NULL
FROM VOTE v
WHERE v.person_id = p.id
AND v.article_id = 67388)
UNION比UNION ALL
慢,因为它会删除重复项。如果你想要重复,只需在“UNION”之后添加“ALL”关键字。
答案 1 :(得分:0)
第1项:select id,name from person where id not in (select person_id from vote)
第2项:select id,name from person where id not in (select person_id from vote where article_id = 67388)