在此查詢中,我需要顯示左表中的所有記錄,並且只顯示右表中所有結果爲最高日期的記錄。從第二個表中只加入一行,如果不存在行返回null
目前查詢:
SELECT a.*, c.*
FROM users a
INNER JOIN payments c
ON a.id = c.user_ID
INNER JOIN
(
SELECT user_ID, MAX(date) maxDate
FROM payments
GROUP BY user_ID
) b ON c.user_ID = b.user_ID AND
c.date = b.maxDate
WHERE a.package = 1
這將返回所有記錄中,其中加入是有效的,但我要顯示所有用戶,如果他們沒有付款尚未從支付表中的字段爲空。
我可以用一個工會來顯示其他行:
SELECT a.*, c.*
FROM users a
INNER JOIN payments c
ON a.id = c.user_ID
INNER JOIN
(
SELECT user_ID, MAX(date) maxDate
FROM payments
GROUP BY user_ID
) b ON c.user_ID = b.user_ID AND
c.date = b.maxDate
WHERE a.package = 1
union
SELECT a.*, c.*
FROM users a
--here I would need to join with payments table to get the columns from the payments table,
but where the user doesn't have a payment yet
WHERE a.package = 1
選擇使用工會似乎並不像一個很好的解決方案,但是這是我的嘗試。
我有12c,所以他的答案有效。但我喜歡你的方法+1 – davejal