用于获取具有公共列值的行值的SQL语法

时间:2013-12-16 14:06:13

标签: mysql sql relational-division

我正在使用MySql 5,我想知道是否可以使用sql语法获取以下值。

获取包含在组1以及组2和组3中的值节点。

Hosts | groups
   1      1
   1      2
   1      3
   2      1
   3      1 ----->for this example host 1 and 3 are the value which I need
   3      2
   3      3
   4      1

组1是主列表,我需要将所有主机包括在组1中,这些主机包括在组2和组3中。

如果有可能,有人会举个例子吗?

2 个答案:

答案 0 :(得分:3)

您应该能够使用WHEREGROUP BYHAVING的组合获得结果:

select hosts
from yourtable
where groups in (1, 2, 3)
group by hosts
having count(distinct groups) = 3;

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

您可以尝试这样的事情:

select distinct Hosts
from myTABLE
where Hosts in (
  select Hosts from myTABLE where Groups = 1)
AND Hosts in (
  select Hosts from myTABLE where Groups = 2)
AND Hosts in (
  select Hosts from myTABLE where Groups = 3)
Order by Hosts