gpt4 book ai didi

MySQL 表 UNION 问题

转载 作者:行者123 更新时间:2023-11-29 08:53:33 26 4
gpt4 key购买 nike

我正在尝试在 MySQL 中合并两个表,我使用的查询是:

SELECT qa_invoicesitems.item_code, qa_invoicesitems.item_unitprice,    qa_invoicesitems.item_subtotal, qa_invoicesitems.item_discount, 
qa_invoicesitems.item_total
FROM qa_invoicesitems
RIGHT JOIN qa_invoicesitems_returnlog USING (item_code)
WHERE invoice_code = 17
UNION
SELECT qa_invoicesitems_returnlog.item_code, qa_invoicesitems_returnlog.item_unitprice, qa_invoicesitems_returnlog.item_subtotal,
qa_invoicesitems_returnlog.item_discount, qa_invoicesitems_returnlog.item_total
FROM qa_invoicesitems_returnlog
LEFT JOIN qa_invoicesitems USING (item_code)
WHERE returnlog_code = 9

但我看不到想要的结果。

图形示例.. enter image description here

有人知道我如何才能得到这个结果吗?
注意: qa_invoicesitems_returnlog 替换数据。

代码:1234、1585、23取自(qa_invoicesitems_returnlog),因为它们在两个表中都存在,其余的简单显示。 enter image description here

最佳答案

根据您的评论和您的形象,我会说您想要:

  • 表 2 中 qa_invoicesitems_returnlog = 9 的所有行
  • 表 1 中 invoice_code = 17 的所有行,除了表 2 的输出中已存在的带有 item_id 的行。<

因此,将其写为联合,给您:

SELECT qa_invoicesitems_returnlog.item_code as item_code, 
qa_invoicesitems_returnlog.item_unitprice as item_unitprice,
qa_invoicesitems_returnlog.item_subtotal as item_subtotal,
qa_invoicesitems_returnlog.item_discount as item_discount,
qa_invoicesitems_returnlog.item_total as item_total
FROM qa_invoicesitems_returnlog
WHERE qa_invoicesitems_returnlog.returnlog_code = 9
UNION
SELECT qa_invoicesitems.item_code as item_code,
qa_invoicesitems.item_unitprice as item_unitprice,
qa_invoicesitems.item_subtotal as item_subtotal,
qa_invoicesitems.item_discount as item_discount,
qa_invoicesitems.item_total as item_total
FROM qa_invoicesitems
WHERE qa_invoicesitems.invoice_code = 17
AND NOT EXISTS (SELECT * FROM qa_invoicesitems_returnlog qir2
WHERE qir2.returnlog_code = 9
and qir2.item_code = qa_invoicesitems.item_code)

关键是 NOT EXISTS 子句,该子句从表 1 的结果中排除 (qa_invoiceitems),这些项已存在于表 2 的输出中并且具有匹配的 item_code

关于MySQL 表 UNION 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10540072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com