[英]how to perform an outer join in mysql
I have a table A that contains tree columns, id, users ids and vehicle id.我有一个包含树列、id、用户 id 和车辆 id 的表 A。 And a table B that contains vehicleid, and vehicle name.
以及包含车辆 ID 和车辆名称的表 B。
Table A
---------------------------
| Id | User_id |Vehicle_id|
---------------------------
| 1 | 1 | 2 |
| 2 | 1 | 3 |
| 3 | 1 | 4 |
| 4 | 2 | 2 |
| 5 | 2 | 3 |
| 6 | 4 | 5 |
---------------------------
Table B
-------------------
| Id |Vehicle_name|
-------------------
| 1 | Car |
| 2 | Bike |
| 3 | Plane |
| 4 | Boat |
| 5 | Rocket |
-------------------
Given a user id, I need to get all vehicle names, that doesn't match with table A. I've tried Outer joins, but I can't manage to do get the info that i need.给定用户 ID,我需要获取与表 A 不匹配的所有车辆名称。我尝试过外部连接,但无法获得所需的信息。 For example: Given user id 1, the query should return Car and Rocket.
例如:给定用户 ID 1,查询应返回 Car 和 Rocket。
thanks in advance提前致谢
This is simple enough using not in
or not exists
:这很简单,使用
not in
或not exists
:
select b.*
from b
where not exists (select 1
from a
where a.vehicle_id = b.id and a.user_id = @a_user_id
);
I also thought of using a cross join and was able to get the output in case you are more comfortable with join logic.我还考虑过使用交叉连接,并且能够在您对连接逻辑更满意的情况下获得输出。
SELECT CJOIN.USER_ID, CJOIN.VEHICLE_ID, CJOIN.VEHICLE_NAME
FROM
(SELECT DISTINCT A.USER_ID, B.ID AS VEHICLE_ID, B.VEHICLE_NAME FROM TABLE_A A CROSS JOIN TABLE_B B) CJOIN
LEFT JOIN
TABLE_A D
ON CJOIN.USER_ID = D.USER_ID AND CJOIN.VEHICLE_ID = D.VEHICLE_ID
WHERE D.USER_ID IS NULL AND D.VEHICLE_ID IS NULL;
First, I got all possible combinations of USER_ID
x VEHICLE_ID
by a cross join and used this table in a left join to pull records for which there is no match.首先,我通过交叉
VEHICLE_ID
获得了USER_ID
x VEHICLE_ID
的所有可能组合,并在左VEHICLE_ID
使用此表来提取不匹配的记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.