我遇到查询问题,问题是我在同一张桌子上连续三次加入。
有问题的查询是:
SELECT
o.order_id,
n.title,
c.first_name,
tdv5.tid,
tdv6.name,
tdv8.name AS settlement_month
FROM orders o
join products p on o.product_id = p.nid
join node n on p.nid = n.nid
join customers c on o.customer_email = c.customer_email
join term_node tn on tn.nid = p.nid
join term_data tdv6 on tn.tid = tdv6.tid AND tdv6.vid = 6
left join term_data tdv5 on tn.tid = tdv5.tid AND tdv5.vid = 5
left join term_data tdv8 on tn.tid = tdv8.tid AND tdv8.vid = 8
当我使用此查询时,只有使用 tn.tid 的第一个JOIN才有效。例如,如果最后三个的唯一连接是:
join term_data tdv6 on tn.tid = tdv6.tid AND tdv6.vid = 6
它会正常工作。与
相同left join term_data tdv5 on tn.tid = tdv5.tid AND tdv5.vid = 5
并且
left join term_data tdv8 on tn.tid = tdv8.tid AND tdv8.vid = 8
然而,当我将它们结合起来时,它们根本不起作用。当我合并三个查询时,只有tdv6才有效。
你对错误有什么建议吗?感谢。
答案 0 :(得分:1)
如果您尝试放置WHERE子句,如下所示:
SELECT
o.order_id,
n.title,
c.first_name,
tdv5.tid,
tdv6.name,
tdv8.name AS settlement_month
FROM orders o
join products p on o.product_id = p.nid
join node n on p.nid = n.nid
join customers c on o.customer_email = c.customer_email
join term_node tn on tn.nid = p.nid
join term_data tdv6 on tn.tid = tdv6.tid
left join term_data tdv5 on tn.tid = tdv5.tid
left join term_data tdv8 on tn.tid = tdv8.tid
WHERE
tdv6.vid = 6 and
tdv5.vid = 5 and
tdv8.vid = 8
答案 1 :(得分:0)
你确定你的结论是正确的吗?空值将显示在相同的行中,因此当(5,8)中没有term_data.tid = = tn.tid和term_data.vid的记录时,您将只获取TDV6。这些记录的tid和/或settlement_month将为NULL。
您是否也想要加入tdv6?它现在是一个内部联接,这意味着您需要tdv6中的记录才能从tdv5或tdv8获取具有相同tid的记录。