假设我有以下模型:
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有一个一对多表(促销)的外键列,而他又拥有礼物的外键;我有以下有效的查询,但我发现应该有一种比做很多这样的连接更优雅的方法来解决问题:
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;
我如何以更优雅的方式解决查询?提前致谢!