我在一个可能很容易解决的问题上被困了好几个小时但是我迷失了......
我有3张桌子:
用户
id name
----------
1 jack
2 john
...
车
id name
----------
1 ford
2 fiat
3 alfa
4 lada
...
user_car
id_user id_car
-----------------
1 2
1 4
2 1
2 2
2 3
例如,我想让所有用户在 user_car 表中拥有ID为1和2的汽车,所以我应该只获取id_user 2而我找不到正确的方法它
答案 0 :(得分:0)
尝试这个未经测试的查询:
select * from user join user_car car1 on id =car1.user_id
join user_car car2 on id =car2.user_id where car1.id_car=1 and car2.id_car=2
答案 1 :(得分:0)
我会在这件事上使用UNION:
SELECT id as id_user from user where id in(1, 2)
UNION
SELECT id as id_car from car where id in (1, 2)
答案 2 :(得分:0)
可能你想要这个
SELECT *
FROM USER
WHERE id IN
(SELECT id_user
FROM user_car
WHERE id_car=1 OR id_car=2);
答案 3 :(得分:0)
您可以使用COUNT执行此操作: -
SELECT user.name
FROM user
INNER JOIN user_car ON user.id = user_car.id_user
INNER JOIN car ON user_car.id_car = car.id
WHERE car.id IN (1,2)
GROUP BY user.name
HAVING COUNT(DISTINCT car.id) = 2
请注意,当您使用汽车的ID时,可以简化此操作以消除对汽车桌的需求。