MySQL对三个相互连接的表的联接查询

时间:2018-08-16 06:06:13

标签: mysql sql

我有三个这样的表:

动物

| id | cat_id | horse_id | dog_id |
|:--:|:------:|:--------:|--------|
|  1 |   15   |    16    | 17     |

| id | lang_id |
|:--:|:-------:|
| 15 |   3716  | 

| id | lang_id |
|:--:|:-------:|
| 16 |   3717  | 

| id | lang_id |
|:--:|:-------:|
| 17 |   3718  | 

语言

|  id  |      en        |
|:----:|:--------------:|
| 3716 | BRAVE LEGEND   |
| 3717 | N Rawiller     |
| 3718 | DRAGON GENERAL |

我想从en表中通过每只动物的表Language获得所有动物lang_id的名称。就像使用Animalcat_id-> Catlang_id-> Languageen。最终结果将是:

| animal_id |   cat_name   | horse_name |    dog_name    |
|:---------:|:------------:|:----------:|:--------------:|
|     1     | BRAVE LEGEND | N Rawiller | DRAGON GENERAL |

我正在尝试使用此

select animal.id, lang.* from animal 
left join cat on animal.cat_id = cat.id
left join horse on animal.horse_id = horse.id
left join dog on animal.dog_id = dog.id
left join lang on cat.lang_id = lang.id or (horse.lang_id = lang.id) or (dog.lang_id = lang.id)
where animal.id = 1

但是我无法获得cat_namedog_namehorse_name,因为它们都来自同一个Language表。

3 个答案:

答案 0 :(得分:0)

请尝试以下查询:

您需要多次JOIN lang表,将一个JOIN与多个OR配合使用将不会获得期望的结果,

SELECT animal.id, lang.en as cat_name,l1.en as horse_name,l2.en as dog_name 
FROM animal 
      LEFT JOIN cat ON animal.cat_id = cat.id
      LEFT JOIN horse ON animal.horse_id = horse.id
      LEFT JOIN dog ON animal.dog_id = dog.id
      LEFT JOIN lang ON cat.lang_id = lang.id 
      LEFT JOIN lang l1 ON horse.lang_id = l1.id 
      LEFT JOIN lang l2 ON dog.lang_id = l2.id
WHERE animal.id = 1

答案 1 :(得分:0)

尝试一下:

select animal.id, lang1.cat_name, lang2.horse_name, lang3.dog_name  
from animal 
left join cat on animal.cat_id = cat.id
left join horse on animal.horse_id = horse.id
left join dog on animal.dog_id = dog.id
left join lang AS lang1 on cat.lang_id = lang1.id 
left join lang AS lang2 ON horse.lang_id = lang2.id 
left join lang AS lang3 ON (dog.lang_id = lang3.id)
where animal.id = 1

答案 2 :(得分:0)

Try this:
SELECT a.id, lang1.en  as cat_name,lang2.en as horse_name,lang3.en as dog_name
FROM  `animal` a
LEFT JOIN cat c ON c.id = a.cat_id 
LEFT JOIN LANGUAGE l on l.id=c.lang_id
LEFT JOIN dog d ON d.id = a.dog_id
LEFT JOIN horse h ON h.id = a.horse_id
LEFT JOIN language lang1 ON c.lang_id=lang1.id
LEFT JOIN language lang2 ON h.lang_id=lang2.id
LEFT JOIN language lang3 ON d.lang_id=lang3.id