Mysql 查询关联表上的外键
假设我有以下模型:Mysql 查询关联表上的外键,mysql,associations,Mysql,Associations,假设我有以下模型: Customer(customer_id (PK), firstName, lastName, email) Item(item_id (PK), name, description) Orders(orders_id (PK), customer_id (FK), item_id (FK), promotion_id (FK)), Promotion(promotion_id (PK), date, gift_id (FK)) Gift(gift_id (PK), name
Customer(customer_id (PK), firstName, lastName, email)
Item(item_id (PK), name, description)
Orders(orders_id (PK), customer_id (FK), item_id (FK), promotion_id (FK)),
Promotion(promotion_id (PK), date, gift_id (FK))
Gift(gift_id (PK), name, description)
现在,假设我有以下要求:
检索来自所有客户的所有订单列表(不按分组),以及来自关联项目和礼品的名称列
困难的部分是,关联表orders的一对多表(promotion)有一个外键列,而promotion的外键又是gift的外键;
我有下面的查询,但我发现它应该有一种更优雅的方法来解决问题,而不是像这样进行大量连接:
select concat(c.firstName, ' ', c.lastName) as customerName,
i.name, g.name
from customer as c
left join orders as o on c.customer_id = o.customer_id
inner join item as i on o.item_id = i.item_id
inner join promotion as p on o.promotion_id = p.promotion_id
inner join gift as g on p.gift_id = g.gift_id;
如何以更优雅的方式解决查询?
提前谢谢 我觉得这非常优雅。连接非常经典,经常被误解。您可以删除
内部的关键字,因为默认情况下连接是内部的,而as
关键字是可选的;另外,由于联接中的列名相同,因此可以简单地使用USING
而不是ON
:
SELECT CONCAT_WS(' ', c.firstName, c.lastName) customerName,
i.name, g.name
FROM customer c
LEFT JOIN orders o USING (customer_id)
JOIN item i USING (item_id)
JOIN promotion p USING (promotion_id)
JOIN gift g USING (gift_id)
事实上,如果这些列在连接的表中是唯一具有相同名称的列,则可以进一步使用NATURAL
连接(尽管我不喜欢这样,因为它隐藏了模式更改时发生的情况):
我更喜欢指定内部连接,而不仅仅是连接,只是为了确认这是您真正想要的。
SELECT CONCAT_WS(' ', c.firstName, c.lastName) customerName,
i.name, g.name
FROM customer c
NATURAL LEFT JOIN orders o
NATURAL JOIN item i
NATURAL JOIN promotion p
NATURAL JOIN gift g