SQL从表1中选择一行连接表2中的多行

时间:2014-08-04 17:35:46

标签: mysql join sql

所以我有两个表,第一个是用户_

Name
------
Carol
Sue

第二个是兴趣_

Name        Interest
----------------------
Carol       Books
Carol       Dancing
Carol       Sports    
Sue         Books
Sue         Dancing

将向用户显示复选框,以根据类似兴趣的标准选择匹配,例如

enter image description here

因此,如果用户选择书籍和舞蹈作为他们的匹配兴趣,我将构建什么类型的SQL查询以组合多个兴趣行并确保结果是苏,因为她有书籍和舞蹈作为兴趣但不是体育?

任何帮助都会有很长的路要谢!

5 个答案:

答案 0 :(得分:2)

所以基本上这样做会构建一个负面的用户列表,其中包含超过这两个用户,然后选择其他用户

SELECT u.name 
FROM users_ u     
JOIN interests_ i ON i.name = u.name
JOIN
(   SELECT u.name 
    FROM users_ u
    JOIN interests_ i ON i.name = u.name
    WHERE i.interest NOT IN('Books', 'Dancing')
) t
WHERE u.name <> t.name 
  AND i.interest IN('Books', 'Dancing')
GROUP BY u.name
HAVING COUNT(u.name) = 2;

DEMO

答案 1 :(得分:2)

这是一种简单的方法

select
i.name 
from interests i
where i.interest in ('Books','Dancing')
and not exists
(
  select 1 from interests i1
  where interest not in ('Books','Dancing')
  AND i.name = i1.name
)
group by i.name
having count(*) = 2

<强> DEMO

答案 2 :(得分:1)

实现此结果的一种方法:

SELECT u.name
  FROM users_ u
  JOIN interests_ n01 ON n01.name = u.name AND n01.interest = 'Books'
  JOIN interests_ n02 ON n02.name = u.name AND n02.interest = 'Dancing'
  LEFT JOIN interests_ x01 ON x01.name = u.name AND x01.interest = 'Sports'
  LEFT JOIN interests_ x02 ON x02.name = u.name AND x01.interest = 'Wine'
 WHERE x01.name IS NULL
   AND x02.name IS NULL

这种方法要求“包括”每个兴趣的JOIN,以及“排除”每个兴趣的反连接。这种方法很灵活,但对于大量的兴趣可能变得难以处理。

要仅查找指定兴趣的匹配项,而不必列出所有不匹配的兴趣,我们可以使用反联接查找不匹配的兴趣行:

SELECT u.name
  FROM users_ u
  JOIN interests_ n01 ON n01.name = u.name AND n01.interest = 'Books'
  JOIN interests_ n02 ON n02.name = u.name AND n02.interest = 'Dancing'
  LEFT
  JOIN interests_ o 
    ON o.name = u.name
   AND o.interest NOT IN ('Books','Dancing')
 WHERE o.name IS NULL

另一种方法是使用JOIN操作和COUNT()聚合,例如

SELECT u.name
  FROM users_ u
  JOIN interests_ n 
    ON n.name = u.name 
   AND n.interest IN ('Books','Dancing')
  LEFT
  JOIN interests_ o
    ON o.name = u.name
   AND o.interest NOT IN ('Books','Dancing')
 WHERE o.name IS NULL
 GROUP BY u.name
HAVING COUNT(DISTINCT n.interest) = 2

还有其他一些方法(这些只是一些例子)。

答案 3 :(得分:0)

使用SQL in运算符

select * from  interests_ where Interest in ('Books', 'Dancing') and Interest not in ('Sports');

编辑1

这对我有用

SELECT * FROM user_ WHERE EXISTS ( 
    SELECT i.Name, count(distinct i.Interest) FROM interests_ as i
    WHERE i.Name=user_.Name
    AND i.Interest IN ('Books','Dancing')
    GROUP BY i.Name
    HAVING count(distinct i.Interest) = 2
);

参考:SQL equivalent of IN operator that acts as AND instead of OR?

答案 4 :(得分:-1)

左连接非常有用。你可以试试这个。

SELECT users_.*
FROM users_
    LEFT JOIN interests_
    ON users_.Name = Interests_.Name
            WHERE interests_.Interests = 'Books'
            AND interests_.Interests = 'Dancing'