如何使用"其中"在加入两个表?

时间:2018-01-29 09:27:15

标签: mysql sql

主表:

(跳闸)

id | name
1  | USA
2  | Europe
3  | Asia

儿童:

(plane)
id | trip_id | name | other
1  |    1    | aaa  |  w
2  |    1    | bbb  |  e
3  |    3    | ccc  |  rr

(boat)
id | trip_id | name
1  |    2    | jjj
2  |    2    | kkk
3  |    3    | lll

如果我想乘飞机旅行,那么我可以:

SELECT trip.* FROM trip INNER JOIN plane ON plane.trip_id = trip.id

如果我想乘船去旅行,那么我可以:

SELECT trip.* FROM trip INNER JOIN boat ON boat.trip_id = trip.id

但如何使用飞机或船只(或两者)进行一次查询?

5 个答案:

答案 0 :(得分:3)

只需使用UNION ALL

SELECT trip.* FROM trip INNER JOIN plane ON plane.trip_id = trip.id
UNION ALL
SELECT trip.* FROM trip INNER JOIN boat ON boat.trip_id = trip.id

答案 1 :(得分:2)

您可以通过LEFT加入

来实现
SELECT trip.*,ifnull(plane.Name,'NA') as planetrip, ifnull(boat.Name,'NA')  boattrip FROM trip 
LEFT JOIN plane ON plane.trip_id = trip.id
LEFT JOIN boat ON boat.trip_id = trip.id
WHERE (plane.Name IS NOT NULL OR boat.Name IS NOT NULL)

SQL DEMO:http://sqlfiddle.com/#!9/2ae5c/10

答案 2 :(得分:2)

尝试将trip表连接到其他两个表。这里的诀窍是我们最后通过旅行进行汇总,并检测每次旅行中是否有飞机或船只表中的匹配。

SELECT t.id, t.name,
    CASE WHEN COUNT(p.trip_id) > 0 THEN 'yes' ELSE 'no' END AS has_plane,
    CASE WHEN COUNT(b.trip_id) > 0 THEN 'yes' ELSE 'no' END AS has_boat
FROM trip t
LEFT JOIN plane p
    ON t.id = p.trip_id
LEFT JOIN boat b
    ON t.id = b.trip_id
GROUP BY t.id;

    id  name    has_plane   has_boat
1   1   USA     yes         no
2   2   Europe  no          yes
3   3   Asia    yes         yes

Demo

答案 3 :(得分:1)

您可以使用左连接,如下所示

select trip.*, isnull(plane.name, '-') as PlaneName, isnull(boat.name, '-') as BoatName from trip left join plane ON plane.trip_id = trip.id left JOIN boat ON boat.trip_id = trip.id

它将返回下表,随意使用这3个表中任何一个的任何字段...

enter image description here

答案 4 :(得分:1)

如果您想要在多行上获得所有结果,可以使用UNION 但你的桌面和船的列数不同,所以你应该使用带有明确列名的联合,例如:

  SELECT trip_id, plane.name, trip.name
  from plane
  inner join trip on trip.id = plane.trip_id
  UNION 
  SELECT trip_id, plane.name, trip.name
  from bout
  inner join trip on trip.id = boat.trip_id

或者如果您需要所有值,则必须在需要时使用空列

  SELECT trip_id, plane.name, trip.name, other
  from plane
  inner join trip on trip.id = plane.trip_id
  UNION 
  SELECT trip_id,plane.name, trip.name, null
  from bout
  inner join trip on trip.id = boat.trip_id