通过refTabels查询

时间:2011-10-08 01:05:07

标签: mysql sql doctrine

我有这个标签

用户:

id name
1 | tom
2 | jim
3 | bob

User_Has_Toys

user_id toy_id
1      | 2
1      | 3
1      | 4
2      | 2
2      | 4
3      | 4

玩具

id name
1 | toy1
2 | toy2
3 | toy3
4 | toy4
5 | toy5

我查询

SELECT u.id FROM Users u
LEFT JOIN User_Has_Toys uht ON (u.id = uht.user_id)
LEFT JOIN Toy t ON t.id = uht.toy_id
WHERE t.id IN ('2', '4')

我得到了所有用户 但我只需要id为1和2的用户

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

 DECLARE @User TABLE
 (
UserID INT NOT NULL,
Name VARCHAR(128)
 )

 DECLARE @User_Has_Toys TABLE
 (
    UserID INT NOT NULL,
ToyID INT NOT NULL
 )

 DECLARE @Toys TABLE
 (
ToyID INT NOT NULL,
ToyName VARCHAR(128)
 )

 INSERT INTO @User (UserID, Name) VALUES (1,'Tom')
 INSERT INTO @User (UserID, Name) VALUES (2,'Jim')
 INSERT INTO @User (UserID, Name) VALUES (3,'Bob')

 INSERT INTO @User_Has_Toys (UserID, ToyID) VALUES (1,2)
 INSERT INTO @User_Has_Toys (UserID, ToyID) VALUES (1,3)
 INSERT INTO @User_Has_Toys (UserID, ToyID) VALUES (1,4)
 INSERT INTO @User_Has_Toys (UserID, ToyID) VALUES (2,2)
 INSERT INTO @User_Has_Toys (UserID, ToyID) VALUES (2,4)
 INSERT INTO @User_Has_Toys (UserID, ToyID) VALUES (3,4)

 INSERT INTO @Toys (ToyID, ToyName) VALUES (1,'Toy1')
 INSERT INTO @Toys (ToyID, ToyName) VALUES (2,'Toy2')
 INSERT INTO @Toys (ToyID, ToyName) VALUES (3,'Toy3')
 INSERT INTO @Toys (ToyID, ToyName) VALUES (4,'Toy4')
 INSERT INTO @Toys (ToyID, ToyName) VALUES (5,'Toy5')


 SELECT 
 u.UserID,
 u.Name,
 uht.ToyID,
 t.ToyName
 FROM @User AS u
 LEFT JOIN @User_Has_Toys AS uht ON u.UserID = uht.UserID
 LEFT JOIN @Toys AS t ON t.ToyID = uht.ToyID
 WHERE uht.ToyID IN (2,4)

 This one is good for SQL Server 2008 r2 
 don't mind the temp tables I've just used them to represent you're sample table. 

答案 1 :(得分:1)

检查用户是否在另一个表中有多个特定行的一种方法是过滤这些行并查看count是否正确。因此,例如,如果我们计算User_Has_Toys中特定用户ID的行数并过滤玩具2和4,那么当且仅当用户同时拥有玩具2和4时,我们才会得到2的计数(注意:假设不允许重复的玩具条目)。查询看起来像这样:

 SELECT 
     u.id
 FROM Users AS u
    WHERE 2 = (
        SELECT COUNT(*) FROM User_Has_Toys uht
        WHERE uht.toy_id IN (2,4)
        AND uht.user_id = u.id);

演示:http://sqlize.com/6yU3OlU2pD

您还可以通过对用户ID进行分组并检查玩具数量是否为2来对原始查询进行微小修改,从而获得相同的结果:

SELECT u.id FROM Users u
LEFT JOIN User_Has_Toys uht ON (u.id = uht.user_id)
LEFT JOIN Toy t ON t.id = uht.toy_id
WHERE t.id IN ('2', '4')
group by u.id having count(t.id) = 2;

演示:http://sqlize.com/7nTYZbJKsn