如果两个不同行中的值匹配条件,MySQL查询将返回一个值

时间:2019-12-22 18:34:20

标签: mysql

在下面的示例中,我尝试创建一个查询,如果该查询同时包含'硝酸铵''脲',则返回NAME的内容。事实是,它们位于单独的行中,但我还没有找到如何检查两者的方法。我曾尝试使用条款INANDUNION,但无济于事。

该查询应仅返回“快速” ,因为它是唯一包含两者的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!

1 个答案:

答案 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