简体   繁体   English

从另一张表的一列中的多个值中选择唯一的ID

[英]Select unique ids from multi values on one column in another table

I'm stuck for hours on an issue that might be pretty simple to solve but I'm just so lost... 我在一个问题上停留了几个小时,这个问题可能很容易解决,但我迷失了……

I got 3 tables : 我有3张桌子:

user 用户

id    name
----------
1     jack
2     john
...

car 汽车

id    name
----------
1     ford
2     fiat
3     alfa
4     lada
...

user_car user_car

id_user    id_car
-----------------
1          2
1          4
2          1
2          2
2          3

For example, i want to get all users with cars which have id 1 AND 2 in the user_car table so I should get the id_user 2 only and I can't find the proper way to do it. 例如,我想让所有用户在user_car表中拥有ID为1和2的汽车,因此我应该只获得id_user 2,而我找不到正确的方法。

try this untested query: 试试这个未经测试的查询:

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

I would use UNION for this matter: 我将在此问题上使用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)

May be you want this 也许你想要这个

SELECT *
FROM USER
WHERE id IN
    (SELECT id_user
     FROM user_car
     WHERE id_car=1 OR id_car=2);

You can use COUNT to do this:- 您可以使用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 

Note that this could be simplified to remove the need for the car table when you are just using the id of the car. 请注意,当您仅使用汽车ID时,可以简化此操作以消除对汽车桌子的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM