我有以下架构,表上的字段owner_id,billing_id,tech_id,admin_id
指向carts
表contacts
。正如您从查询结果中看到的那样,我必须JOIN
为每个字段。有没有办法避免?
SELECT c.domain, c.period, co.name AS owner, co1.name AS admin, co2.name AS tech, co3.name AS billing, h.nameserver
FROM carts c
LEFT JOIN contacts co ON c.owner_id = co.id
LEFT JOIN contacts co1 ON c.admin_id = co1.id
LEFT JOIN contacts co2 ON c.tech_id = co2.id
LEFT JOIN contacts co3 ON c.billing_id = co3.id
LEFT JOIN HOSTS h ON c.host_id = h.id
WHERE c.user_id =1
只需一个 join 和 pivoting 就可以获得相同的结果。
但是,检查两个版本的执行计划,有时多个连接可能比这种方法更快。