这个mysql连接怎么写
我有下表
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、成分_id2、成分_id3
列是“成分”表的外键,我的要求是创建一个选择查询来显示项目和成分,如下
select id, code, name, price, name as ingredient_name1, name as ingredient_name2, name as ingredient_name3
但我不这样做知道如何连接同一个表3次,有人可以帮助我理解这个连接条件
I have the following table
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 | |
+-------------------+--------------+------+-----+---------+----------------+
and my ingredients table
mysql> desc ingredients;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
and ingredient_id, ingredient_id2, ingredient_id3
columns are foreign keys of 'ingredients' table, my requirement is to create a select query to display items and ingredients as follows
select id, code, name, price, name as ingredient_name1, name as ingredient_name2, name as ingredient_name3
But I dont know how to join the same table 3 times, can someone help me to understand this join condition
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
TRY
您好,您可以使用具有不同别名的同一个表。
成分 AS In1
成分 AS In2
成分 AS In3
Hi You can use the same table with different alias.
ingredients AS In1
ingredients AS In2
ingredients AS In3
我认为这就是您正在寻找的:
I think this is what you are looking for: