查找表

时间:2015-10-29 17:55:14

标签: sql

假设我们有一个包含两列{@ 1}}和name的表格。每个likes可能有多个name

我需要一个查询来查找与likes具有完全相同的names的{​​{1}}(并不包含在Bob中,而不是更多包含Bob的所有内容。)< / p>

我的想法是针对每个likes,将他们的name=Bob加入Bob的name并检查它是否与Bob likes匹配,同时还要检查每个人是否具有相同的号码likes。有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

你需要在这里自我加入。这意味着将表连接到自身,如下所示 -

Select distinct a.name, b.name from table as a join      table as b on a.likes = b.likes and a.name != b.name

注意使用distinct子句和名称不等式来避免名称与自身匹配

这将输出行 -

a.name  |  b.name
----------------------------
Bob         |  John
Smith      |  Ram

如果要将特定用户检查为Bob,则可以在查询中附加where子句。

答案 1 :(得分:0)

一种方法是将变量连接成一个字符串并进行比较。使用MySQL语法:

select t.name
from (select name, group_concat(likes order by likes) as likes
      from t
      group by name
     ) t cross join
     (select group_concat(likes order by likes) as likes
      from t
      where name = 'Bob'
     ) bob
     on t.likes = bob.likes and t.name <> 'Bob';

在几乎任何其他数据库中都可以使用的另一种方法是使用连接并计数:

select t.name
from (select t.*, count(*) over (partition by name) as numlikes
      from t
      where name <> 'Bob'
     ) t cross join
     (select t.*, count(*) over (partition by name) as numlikes
      from t
      where name = 'Bob'
    ) bob
    on t.likes = bob.likes and t.cnt = bob.cnt
group by t.name, t.cnt
having count(*) = t.cnt;  -- the number of matches is the number of likes