sql - MySQL: Return all rows with same ID but filter by a different field -
in application, have table identifies resources (i.e. pictures) id. said resources have been "tagged" (field1). i.e. picture 3 in table below tagged both 'a' , 'b'. whereas picture 1 tagged 'a' , picture 2 tagged 'b'.
here "tagging" table:
+--------------+ | id | field1 | +--------------+ | 1 | | | 2 | b | | 3 | | | 3 | b | +--------------+
note: id's neither unique nor auto-incrementing.
problem: want return pictures tagged 'b', not want return tagged 'a'.
select id pictures field1 = 'b';
returns:
+-----+ | id | +-----+ | 2 | | 3 | +-----+
this not want want, because includes picture 3 tagged 'a' (in row preceding [3, b] in original table)
i want:
+-----+ | id | +-----+ | 2 | +-----+
here 2 methods:
exists subclause:
select id pictures pictures1 field1 = 'b' , not exists ( select * pictures picutures2 pictures2.id = pictures1.id , pictures2.field1 = 'a');
left join:
select pictures1.id pictures pictures1 left join pictures picutures2 on pictures2.id = pictures1.id , pictures2.field1 = 'a' pictures1.field1 = 'b' , pictures2.id null -- line eliminates records join fails; note if have line, must not put other pictures2 references in clause
;
Comments
Post a Comment