在下面的示例中,我尝试创建一个查询,如果该查询同时包含'硝酸铵'和'脲'1>,则返回NAME
的内容。事实是,它们位于单独的行中,但我还没有找到如何检查两者的方法。我曾尝试使用条款IN
,AND
和UNION
,但无济于事。
该查询应仅返回“快速” ,因为它是唯一包含两者的NAME
。
+-------+------------------+-------------+---------+
| FCODE | CNAME | NAME | CONTACT |
+-------+------------------+-------------+---------+
| 28994 | ammonium nitrate | Gro-Fast | 556698 |
| 28994 | urea | Gro-Fast | 556698 |
| 29462 | ammonium nitrate | BetterRoots | 342554 |
| 34588 | ammonium nitrate | Flourisher | 342554 |
| 83732 | urea | GreenAgain | 354211 |
+-------+------------------+-------------+---------+
TIA!
答案 0 :(得分:0)
您可以group by name
并在HAVING
子句中设置条件:
select name
from tablename
where cname in ('ammonium nitrate', 'urea')
group by name
having count(distinct cname) = 2
如果您希望列cname
仅包含 '硝酸铵'和'脲':
select name
from tablename
group by name
having
sum(cname not in ('ammonium nitrate', 'urea')) = 0
and
count(distinct cname) = 2
请参见demo。
结果:
> | name |
> | :------- |
> | Gro-Fast |
针对您的查询进行编辑:
select name
from CONTENTS natural join FERTILIZERS
where cname in ('ammonium nitrate', 'urea')
group by name
having count(distinct cname) = 2