繁体   English   中英

MySql:如何选择所有值都相同的行?

[英]MySql: How to select rows where all values are the same?

我有一张这样的桌子:

name |id | state
name1 12   4
name1 12   4
name2 33   3
name2 33   4
...

我想从状态仅为 4的表中选择每个名称和ID,这意味着name1是正确的,因为它只有两个状态为4的记录,仅此而已。 同时NAME2是错误的,因为它与国家4 记录与状态3纪录。

select name, id from mytable where id not in
(select distinct id from mytable where state <> 4)

您可以使用聚合,如下所示:

SELECT name, id
FROM your_table
GROUP BY name, id
HAVING SUM(state<>4)=0;

请参阅有关SQL Fiddle演示

您可能需要2个子查询。

  1. 按名称分组选择状态4
  2. 按名称分组

比较计数(如果计数相同),然后选择它

示例:从状态= 4的表中选择名称,计数(名称)作为T1选择从名称中的表,计数(名称)作为T2选择从T1和T2中选择T1.name,其中T2.count = T1.count

您可以使用不存在这样的内容:

select distinct name, id 
from table1 a
where not exists (select *
                  from table1 b
                  where  a.id=b.id and state<>4)

在更一般的情况下,您可以使用计数不重复(不存在或具有联接):

select distinct name, id 
from table1 a
where not exists (
select *
from table1 b
where  a.id=b.id
group by id
HAVING count(distinct state)>1)

暂无
暂无

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

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