开发者

How to build this query in sqlite?

开发者 https://www.devze.com 2023-01-10 22:05 出处:网络
I have sqlite3 database with example开发者_JAVA技巧 structure and data: CREATE TABLE person(id INTEGER PRIMARY KEY NOT NULL, name STRING NOT NULL);

I have sqlite3 database with example开发者_JAVA技巧 structure and data:

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);

Now I would like to (in one select query) find all persons witch:

  1. Do not vote at all
  2. Do not vote for article 67388

I have no ideas how to do this :/

help :'(


Using 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)

Using 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 is slower than UNION ALL, because it removes duplicates. If you want duplicates, just add the "ALL" keyword after "UNION".


Item 1: select id,name from person where id not in (select person_id from vote)

Item 2: select id,name from person where id not in (select person_id from vote where article_id = 67388)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号