views:

36

answers:

2

Hello :)

I have sqlite3 database with example 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 :'(

A: 

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)

Ronaldo Junior
Wow it works, but it must be in one select statement, sorry ;)
BPS
+1  A: 

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".

OMG Ponies
Thanks it works great :D (with little change: v.article_id <> 67388)
BPS
@BPS: That'd be because you forgot the `NOT` before the EXISTS
OMG Ponies