![](/img/trans.png)
[英]How do I get rows with value1 in column1 and value2 in column2 but value2 in column1 does not have value1 in column2?
[英]how to get distinct column value1 from a table which does not include a particular value in column value 2 when it has multiple rows with col val1?
可能是一个大头衔! 对此表示抱歉。
Table 1
id col1 col2
1 10 one
2 11 two
3 10 three
现在,我想编写一个SQL查询来从table1中获得不同的col1,而table1在col2中没有三个。 我只需要输出col1-11。
我试过像这样select distinct col1 from table1 where col2 != 'three'
但是结果为10和11。但是对于10,它具有对应的行,其中3作为col2值。 请帮助我找到这个。
使用group by
并having
。
select col1
from table1
group by col
having sum(case when col2='three' then 1 else 0 end)=0
如果你正在使用MySQL时, having
情况可缩短至
select col1
from table1
group by col
having sum(col2='three')=0
因为条件被视为布尔值,返回1表示true,0表示false。
使用not in()
select distinct col1
from table1 t
where col1 not in (
select col1
from table1 i
where i.col2 = 'three'
)
或使用not exists()
select distinct col1
from table1 t
where not exists (
select 1
from table1 i
where i.col1 = t.col1
and i.col2 = 'three'
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.