查询使用两个表

时间:2014-05-22 11:57:20

标签: mysql sql

Table: users
===============
id   | name    |
===============
 1   | steve   |
 2   | peter   |
================

Table: relation_favorites
=======================
| idFavorite | idUser |
=======================
|     1      |   1    |
|     2      |   1    |
|     4      |   1    |
|     5      |   1    |
|     1      |   2    |
|     3      |   2    |
|     4      |   2    |
|     5      |   2    |
=======================

我想选择最喜欢的1 AND 4 AND 5的所有用户。 我认为我需要使用LEFT JOIN,但我无法看到它是如何做到的。

它不起作用:

$query = "SELECT rf.id, u.id idUser
          FROM  users u, relation_favorites rf
          WHERE rf.idUser = u.id
          AND rf.idFavorite = 1
          AND rf.idFavorite = 4
          AND rf.idFavorite = 5";

它有效,但这不是我想要的:

$query = "SELECT rf.id, u.id idUser
          FROM  users u, relation_favorites rf
          WHERE rf.idUser = u.id
          AND rf.idFavorite = 1";

3 个答案:

答案 0 :(得分:2)

使用JOIN和COUNT: -

SELECT u.id AS idUser, COUNT(rf.idFavorite) AS favourite_count
FROM  users u
INNER JOIN relation_favorites rf
ON rf.idUser = u.id
WHERE rf.idFavorite IN (1, 4, 5)
GROUP BY idUser
HAVING favourite_count = 3

您还可以使用多个联接: -

SELECT u.id AS idUser
FROM  users u
INNER JOIN relation_favorites rf1
ON rf1.idUser = u.id AND rf1.idFavorite = 1
INNER JOIN relation_favorites rf2
ON rf2.idUser = u.id AND rf2.idFavorite = 4
INNER JOIN relation_favorites rf3
ON rf3.idUser = u.id AND rf3.idFavorite = 5

答案 1 :(得分:0)

Select name from user 
where id in
(Select distinct idUser from relation_favorites wher  idFavorite in(1,4,5))

试试这个子查询可能适合你。

您可能会尝试这两个查询输出相同

Select distinct name from user x
join relation_favorites y
on x.Id=y.IdUser
where y.idFavorite in(1,4,5)

编辑:尝试此查询

Select x.Name from Users x
join relation_favorites y
on x.Id=y.IdUser
where y.idFavorite in (1,3,4)
Group By x.Name
Having Count(y.IdUser)=3

答案 2 :(得分:-1)

尝试此查询。

select u.id,u.name,rf.idFavorite,rf.idUser from users u,relation_favorites rf where rf.idFavorite = u.id and rf.idFavorite IN (1,4,5);

希望它有效