在SQL UNION之后替换NULL列

时间:2016-11-22 17:17:44

标签: sql postgresql

我使用UNION来组合两个select语句的结果。在一个声明中,我找到了identity的{​​{1}},而在另一个声明中,我找到了sender的{​​{1}}。我遇到的问题是我的行数始终是“应该”的两倍,因为收件人结果总是会出现“空白”identity而“行空白”recipient发件人结果。如何重新构建此项,以便为每个填充了senderrecipient的交易返回一行?

sender

以下是我目前一项交易结果的示例:

recipient

我的目标是:

(
  SELECT s.id, s.sender_id, '' AS sender, NOW() AS sender_create_date, s.recipient_id,
    MAX(c.identity) AS recipient, MAX(c.create_date) AS recipient_create_date
  FROM db.sales s
  LEFT JOIN db.customers c ON c.participant_id = s.recipient_id
  WHERE sender_id = $1
  OR recipient_id = $1
  GROUP BY s.id
)
UNION
(
  SELECT s.id, MAX(c.identity) AS sender, MAX(c.create_date) AS sender_create_date, s.recipient_id,
    '' AS recipient, NOW() AS recipient_create_date
  FROM db.sales s
  LEFT JOIN db.customers c ON c.participant_id = s.recipient_id
  WHERE sender_id = $1
  OR recipient_id = $1
  GROUP BY s.id
)

1 个答案:

答案 0 :(得分:1)

通过两个连接可以完成我的目标:

SELECT s.id, MAX(cs.identity) AS sender, MAX(cs.create_date) AS sender_create_date, MAX(cr.identity) AS recipient, MAX(cr.create_date) AS recipient_create_date
FROM db.sales s
LEFT JOIN db.customers cr ON cr.participant_id = s.recipient_id
LEFT JOIN db.customers cs ON cs.participant_id = s.sender_id
WHERE sender_id = $1
OR recipient_id = $1
GROUP BY s.id;