简体   繁体   English

MySQL获取行仅包含具有特定值的行

[英]Mysql fetch rows only contain a row with certain value

Lets say, my tables has the following rows: 可以说,我的表具有以下行:

  id | prop1 | prop2 
______________________
  1    foo      a
  2    bar      a
  3    foo      b
  4    bar      b
  5    foo      c

Now in this case, i want to get rows grouped by prop1 but ignore the groups that don't contain a row with prop2=c 现在在这种情况下,我想获取按prop1分组的行,但忽略不包含prop2=c的行的组

So the intended result is: 因此,预期结果是:

1 foo a
3 foo b
5 foo c

Note, now there is only one group in the example but i want to be able to get all of them. 请注意,示例中现在只有一组,但是我希望能够全部获得。 How can i achieve this approach? 我如何实现这种方法?

Your expected result is not grouped by prop1 . 您的预期结果未按prop1分组。 If it was grouped by prop1 then you would get only one record in the result. 如果它是按prop1分组的,则结果中将只获得一个记录。

To achieve the above, we can write a simple SELECT with sub-query, eg: 为了达到上述目的,我们可以使用子查询编写一个简单的SELECT ,例如:

SELECT *
FROM table
WHERE prop1 IN (
 SELECT prop1 FROM table WHERE prop2 = 'c'
);

You can use exists clause to remove all the rows if it does not have prop2 = c using below query. 如果不存在prop2 = c,则可以使用exist子句删除所有行,请使用以下查询。

select * 
from your_table t1
where 
exists (select 1 from your_table t2 where t1.prop1 = t2.prop1
        and t2.prop2 = 'c')

Explaination: Exists caluse will return true if it finds c for that group else false. 解释:如果存在针对该组的c,否则现有caluse将返回true。

The following query fetches all record with prop2 = 'c' (T1) and joins them on all records (T2) that have an equal prop1: 以下查询获取prop2 ='c'(T1)的所有记录,并将它们联接到所有具有相同prop1的记录(T2)上:

select T2.*
from    TABLE T1
join TABLE T2 ON T1.prop1=T2.prop1
WHERE T1.prop2 = 'c'
GROUP BY id
SELECT * FROM table WHERE prop2 != "c" GROUP BY prop1

该行将删除带有C的att行,并在prop1上将所有其他内容分组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM