我有下表
mysql> desc items;
+-------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| code | varchar(255) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| price | float | YES | | NULL | |
| ingredient_id | int(11) | YES | | NULL | |
| ingredient_id2 | int(11) | YES | | 0 | |
| ingredient_id3 | int(11) | YES | | 0 | |
+-------------------+--------------+------+-----+---------+----------------+
和我的食材表
mysql> desc ingredients;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
和ingredient_id, ingredient_id2, ingredient_id3
列是'ingredients'表的外键,我的要求是创建一个select查询来显示项目和成分,如下所示
select id, code, name, price, name as ingredient_name1, name as ingredient_name2, name as ingredient_name3
但我不知道如何加入同一张桌子3次,有人可以帮我理解这种加入条件
答案 0 :(得分:3)
select items.id,
code,
name,
price,
in_1.name as ingredient_name1,
in_2.name as ingredient_name2,
in_3.name as ingredient_name3
from items
join ingredients as in_1 on items.ingredient_id = in_1.id
join ingredients as in_2 on items.ingredient_id2 = in_2.id
join ingredients as in_3 on items.ingredient_id3 = in_3.id
答案 1 :(得分:1)
您好您可以使用具有不同别名的同一个表。
成分AS In1 成分AS In2 成分AS In3
答案 2 :(得分:1)
TRY
SELECT i.id, i.name, i.code, i.price,
ig1.name AS igName1,ig2.name AS igName2,ig3.name as igName3
FROM items i
INNER JOIN ingredients ig1 ON ig1.id=i.ingredient_id
INNER JOIN ingredients ig2 ON ig2.id=i.ingredient_id2
INNER JOIN ingredients ig3 ON ig3.id=i.ingredient_id3
答案 3 :(得分:1)
我认为这就是你要找的东西:
select it.id, it.code, it.name, it.price,
ing1.name as name1, ing2.name as name2, ing3.name as name3
from items it, ingredients ing1, ingredients ing2, ingredients ing2
where it.ingredient_id = ing1.id
and it.ingredient_id2 = ing2.id
and it.ingredient_id3 = ing3.id