2016-01-07 43 views
0

在我的应用程序中,我有一个通过其ID标识资源(即图片)的表。所述资源也被“标记”(字段1)。即下表中的图片3用'A'和'B'标记。而图片1仅标有'A',而图片2标有'B'。MySQL:返回具有相同ID但具有不同字段的所有行

这里是我的“标签”表:

+--------------+ 
| id | field1 | 
+--------------+ 
| 1 |  A | 
| 2 |  B | 
| 3 |  A | 
| 3 |  B | 
+--------------+ 

注意:ID是唯一既没有,也没有自动递增。

问题:我想返回标记为'B'的所有图片,但我不想返回标记为'A'的任何图片。

图片中的SELECT ID WHERE field1 ='B';

返回:

+-----+ 
| id | 
+-----+ 
| 2 | 
| 3 | 
+-----+ 

这不是要我要,因为它包括图片3也被标记为“A”(在该行中紧接在前的[3,B]在原始表)

我想:

+-----+ 
| id | 
+-----+ 
| 2 | 
+-----+ 
+0

你怎么能有一个重复的ID? – genespos

+0

@genespos它不是一个独特的ID。 – m0rph3us

+0

定义'上一行' - 或者行不是'上一个'? – Strawberry

回答

1

这里有两种方法:

存在子条款:

SELECT id 
from pictures as pictures1 
WHERE field1 = 'B' 
and not exists ( 
    select * 
    from pictures as picutures2 
    where pictures2.id = pictures1.id 
    and pictures2.field1 = 'A'); 

左连接:

Select pictures1.id 
from pictures as pictures1 
left join pictures as picutures2 on 
    pictures2.id = pictures1.id 
    and pictures2.field1 = 'A' 
where pictures1.field1 = 'B' 
and pictures2.ID is null -- this line eliminates records where the join fails; note that if you have this line, you must not put any other pictures2 references in this where clause 

;

0

你与你的要求就开始了。只要取消选择行,其中字段1是A:

SELECT id from pictures WHERE field1 = 'B' AND id NOT IN(
    SELECT id from pictures WHERE field1 = 'A' 
); 
0

您也可以在一个查询中使用一些聚集达到您想要的结果

select id 
from table1 
group by id 
having sum(field1 = 'B') > 0 
and sum(field1 = 'A') = 0 

DEMO

0
SELECT id 
FROM pictures 
GROUP BY id 
HAVING (GROUP_CONCAT(DISTINCT fuild1)) = 'B' 
相关问题