[英]MySql: How to select rows where all values are the same?
I have a table like this: 我有一张这样的桌子:
name |id | state
name1 12 4
name1 12 4
name2 33 3
name2 33 4
...
I want to select every name and id from table where state is only 4, that means name1 is correct, because it only has two records with state 4 and nothing more. 我想从状态仅为 4的表中选择每个名称和ID,这意味着name1是正确的,因为它只有两个状态为4的记录,仅此而已。 Meanwhile name2 is wrong, because it has record with state 4 and record with state 3. 同时NAME2是错误的,因为它与国家4 和记录与状态3纪录。
select name, id from mytable where id not in
(select distinct id from mytable where state <> 4)
You can use aggregation as shown below: 您可以使用聚合,如下所示:
SELECT name, id
FROM your_table
GROUP BY name, id
HAVING SUM(state<>4)=0;
See a Demo on SQL Fiddle . 请参阅有关SQL Fiddle的演示 。
you might need 2 sub queries . 您可能需要2个子查询。
compare the count if the count is same then select it 比较计数(如果计数相同),然后选择它
example : select name , count (name) from table where state = 4 as T1 select name , count (name) from table as T2 select T1.name from T1 and T2 where T2.count = T1.count 示例:从状态= 4的表中选择名称,计数(名称)作为T1选择从名称中的表,计数(名称)作为T2选择从T1和T2中选择T1.name,其中T2.count = T1.count
You can use not exists like this: 您可以使用不存在这样的内容:
select distinct name, id
from table1 a
where not exists (select *
from table1 b
where a.id=b.id and state<>4)
In a more general case you can use count distinct (with not exists or with a join): 在更一般的情况下,您可以使用计数不重复(不存在或具有联接):
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.