mysql join 外键_多表连接MySQL多个外键

本文探讨了在MySQL中实现四表联接查询时遇到的问题,并提供了一个有效的解决方案。文章详细介绍了如何正确地使用JOIN语句来获取所需的全部字段信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bd96500e110b49cbb3cd949968f18be7.png

I am having difficult times with joins in MySQL. I have 4 tables, all connected together.

**Order**: order_id, shop_id(fk), date, day, order_price, PK_order

**Scan** : scan_id(PK), item_id, order_id(FK), stack, stack_price, price, note

**Item** : item_id(PK), item_name

**Shop** : shop_id(PK), shop_name

I want to build a query that outputs something like this:

date|day|shop_name|item_name|stack|stack_price|price|note

My query looks like this:

Select

order.date, order.day, shop.shop_name, item.item_name, scan.stack, scan.stack_price,

scan.price, scan.note

From

order, scan, shop, item

Join

shop on order.shop_id = shop.shop_id

Join

item on scan.item_id = item.item_id

I get error 1054: Unknown column ... in 'on clause', or the other 'alias' error.

However when I select only one column from one table, i get it working.

This query works:

select item.item_name from scan inner join item on scan.item_id = item.item_id

I think there is some problem with selecting from multiple tables... Anyone can help me? Every reply is appreciated. Thanks

解决方案

You have combined comma separated join and Inner join where you have used same table more than once which is not needed.

If am not wrong this is what you are looking for

SELECT `order`.`DATE`,

`order`.`day`,

shop.shop_name,

item.item_name,

scan.stack,

scan.stack_price,

scan.price,

scan.note

FROM `order`

join scan

ON `order`.order_id = scan.order_id

join shop

ON `order`.shop_id = shop.shop_id

join item

ON scan.item_id = item.item_id

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值