使用UNION显示mysql中两个表的两列

时间:2013-07-24 18:33:21

标签: mysql

我有一个SQL查询,我必须从两个不同的表中获取值(Say a1,a2)。由于简单的原因它可以工作,但因为我在同一个查询中有一个UNION是一个重要的原因(从表a2获取一个值放在a1的列值之间)由于这个原因我的查询结果变得很奇怪。这是我的查询和图像,显示相同TICKET_ID的重复条目,我想删除它,如何?

QUERY

SELECT 
 RECEIPTS.DATENEW AS DATE,
 TICKETS.TICKETID AS TICKETID,
 PAYMENTS.PAYMENT AS PAYMENT,
 PAYMENTS.TOTAL AS TOTAL,
 CUSTOMERS.NAME AS NAME,
 ADJUSTMENTS.ADJUSTMENT_REASON AS REASON
FROM RECEIPTS
 INNER JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID
 INNER JOIN PAYMENTS ON RECEIPTS.ID = PAYMENTS.RECEIPT
 INNER JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID
 RIGHT JOIN ADJUSTMENTS ON ADJUSTMENTS.CUSTOMER_ID = CUSTOMERS.ID
WHERE
 (PAYMENTS.PAYMENT = 'debt'
 OR PAYMENTS.PAYMENT = 'debtpaid')
UNION SELECT 
 ADJUSTMENTS.DATE AS DATE,
 ADJUSTMENTS.TICKET_NO AS TICKETID,
 ADJUSTMENTS.ADJUSTMENT_TYPE AS PAYMENT,
 ADJUSTMENTS.ADJUSTMENT_AMOUNT * -1 AS TOTAL,
 ADJUSTMENTS.CUSTOMER_NAME AS NAME,
 ADJUSTMENTS.ADJUSTMENT_REASON AS REASON
FROM ADJUSTMENTS
 ORDER BY NAME ASC, DATE DESC

,这是它的输出图像

输出

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用GROUP BY或只检查原因列

SELECT q.* FROM (

SELECT 
 RECEIPTS.DATENEW AS DATE,
 TICKETS.TICKETID AS TICKETID,
 PAYMENTS.PAYMENT AS PAYMENT,
 PAYMENTS.TOTAL AS TOTAL,
 CUSTOMERS.NAME AS NAME,
 ADJUSTMENTS.ADJUSTMENT_REASON AS REASON
FROM RECEIPTS
 INNER JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID
 INNER JOIN PAYMENTS ON RECEIPTS.ID = PAYMENTS.RECEIPT
 INNER JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID
 RIGHT JOIN ADJUSTMENTS ON ADJUSTMENTS.CUSTOMER_ID = CUSTOMERS.ID
WHERE
 (PAYMENTS.PAYMENT = 'debt'
 OR PAYMENTS.PAYMENT = 'debtpaid')
UNION SELECT 
 ADJUSTMENTS.DATE AS DATE,
 ADJUSTMENTS.TICKET_NO AS TICKETID,
 ADJUSTMENTS.ADJUSTMENT_TYPE AS PAYMENT,
 ADJUSTMENTS.ADJUSTMENT_AMOUNT * -1 AS TOTAL,
 ADJUSTMENTS.CUSTOMER_NAME AS NAME,
 ADJUSTMENTS.ADJUSTMENT_REASON AS REASON
FROM ADJUSTMENTS
 ORDER BY NAME ASC, DATE DESC ) q GROUP BY q.TICKETID

OR

 ORDER BY NAME ASC, DATE DESC ) q GROUP BY q.REASON !='' // q.REASON IS NOT NULL

答案 1 :(得分:0)

最后我弄清楚了,现在查询变为如下

SELECT
 RECEIPTS.DATENEW AS DATE,
 TICKETS.TICKETID AS TICKETID,
 PAYMENTS.PAYMENT AS PAYMENT,
 PAYMENTS.TOTAL AS TOTAL,
 CUSTOMERS.NAME AS NAME,
 (SELECT ADJUSTMENTS.ADJUSTMENT_REASON FROM ADJUSTMENTS WHERE ADJUSTMENTS.ADJUSTMENT_TYPE != 'adjustment' AND ADJUSTMENTS.ADJUSTMENT_REASON != '') AS REASON
FROM RECEIPTS
 INNER JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID
 INNER JOIN PAYMENTS ON RECEIPTS.ID = PAYMENTS.RECEIPT
 INNER JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID
WHERE
 (PAYMENTS.PAYMENT = 'debt'
 OR PAYMENTS.PAYMENT = 'debtpaid')
UNION SELECT 
 ADJUSTMENTS.DATE AS DATE,
 ADJUSTMENTS.TICKET_NO AS TICKETID,
 ADJUSTMENTS.ADJUSTMENT_TYPE AS PAYMENT,
 ADJUSTMENTS.ADJUSTMENT_AMOUNT * -1 AS TOTAL,
 ADJUSTMENTS.CUSTOMER_NAME AS NAME,
 ADJUSTMENTS.ADJUSTMENT_REASON AS REASON
FROM ADJUSTMENTS
 ORDER BY NAME ASC, DATE DESC