MySQL:返回具有相同ID的所有行,但按不同的字段过滤

时间:2016-01-07 15:46:26

标签: mysql sql

在我的应用程序中,我有一个表,用于通过id识别资源(即图片)。所述资源也被标记为" (FIELD1)。即,下表中的图片3标有' A'和' B'。而图片1仅标有' A'和图片2仅标记为' B'

这是我的#34;标记"表:

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

注意:id既不是唯一的也不是自动递增的。

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

从图片中选择ID WHERE field1 =' B&#39 ;;

返回:

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

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

我想:

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您的请求开始很好。只需取消选择field1为A的行:

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

答案 2 :(得分:0)

您还可以使用单个查询中的某些聚合来实现所需的结果

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

DEMO

答案 3 :(得分:0)

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