0

我正在尝试在 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

但我无法看到预期的结果。

一个图形示例.. 在此处输入图像描述

任何人都知道我怎样才能得到这个结果?
注意: qa_invoicesitems_returnlog 替换数据。

代码:1234、1585、23取自(qa_invoicesitems_returnlog),因为两个表都存在,其余的就简单展示一下。 在此处输入图像描述

4

2 回答 2

1

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

  • 表 2 中的所有行qa_invoicesitems_returnlog = 9
  • 表 1 中的所有行,除了表 2 的输出中已经存在的invoice_code = 17那些行。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

于 2012-05-10T20:50:35.540 回答
1

你为什么使用UNION?我认为以下内容等同于您的查询:

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 = 15 or returnlogcode = 8

LEFT 和 RIGHT 连接做同样的事情,因为表是相反的。

于 2012-05-10T18:34:32.097 回答