iT邦幫忙

0

SQL left join查詢結果重複

sql
  • 分享至 

  • xImage

Confirmations table:
+---------+---------------------+-----------+
| user_id | time_stamp | action |
+---------+---------------------+-----------+
| 3 | 2021-01-06 03:30:46 | timeout |
| 3 | 2021-07-14 14:00:00 | timeout |
| 7 | 2021-06-12 11:57:29 | confirmed |
| 7 | 2021-06-13 12:58:28 | confirmed |
| 7 | 2021-06-14 13:59:27 | confirmed |
| 2 | 2021-01-22 00:00:00 | confirmed |
| 2 | 2021-02-28 23:59:59 | timeout |
+---------+---------------------+-----------+

select ye.* from Confirmations a
left join Confirmations ye on a.user_id = ye.user_id and ye.action = 'confirmed'

Output

user_id time_stamp action
null null null
null null null
7 2021-06-14 13:59:27 confirmed
7 2021-06-13 12:58:28 confirmed
7 2021-06-12 11:57:29 confirmed
7 2021-06-14 13:59:27 confirmed
7 2021-06-13 12:58:28 confirmed
7 2021-06-12 11:57:29 confirmed
7 2021-06-14 13:59:27 confirmed
7 2021-06-13 12:58:28 confirmed
7 2021-06-12 11:57:29 confirmed
2 2021-01-22 00:00:00 confirmed
2 2021-01-22 00:00:00 confirmed

請問為什麼OUTPUT的部份會有資料重複的情況發生?我知道要怎麼去重複,但想知道導致資料重複的原因><

alien663 iT邦研究生 5 級 ‧ 2023-08-07 13:44:02 檢舉
你執行一下,看有沒有慧根自己知道位什麼會有重複

select user_id , action , count(*)
from Confirmations
group by user_id , action
having count(*) >= 2
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
1
Hey
iT邦新手 3 級 ‧ 2023-08-08 09:33:34
最佳解答

https://ithelp.ithome.com.tw/upload/images/20230808/20148067QHUbRSmgVw.png

看圖可能易理解

或者將SQL改成這樣, 你再看DATA會明白

select ye.*, a.* from Confirmations a
left join Confirmations ye on a.user_id = ye.user_id and ye.action = 'confirmed'
0
allenlwh
iT邦高手 1 級 ‧ 2023-08-07 10:18:36

換成 inner join 試試

謝謝大大的回答,可是用inner join還是會導致資料重複><

1
PPTaiwan
iT邦好手 1 級 ‧ 2023-08-07 10:25:33
SELECT *
FROM Confirmations
WHERE user_id IN (
  SELECT user_id
  FROM Confirmations
  WHERE action = 'confirmed'
  GROUP BY user_id
  HAVING COUNT(*) > 1
)
AND action = 'confirmed';
| user_id | time_stamp           | action    |
|---------|----------------------|-----------|
| 7       | 2021-06-12 11:57:29  | confirmed |
| 7       | 2021-06-13 12:58:28  | confirmed |
| 7       | 2021-06-14 13:59:27  | confirmed |

謝謝大大的回答,可以請問大大為什麼我用left join會導致資料重複嗎? ><

PPTaiwan iT邦好手 1 級 ‧ 2023-08-07 10:41:49 檢舉

你的資料

user_id 為 7 的三條 action = 'confirmed' 的記錄組合,結果會是九條記錄。

你下的語法在某些情況下,使用 JOIN 可能會導致重複,你可以再多練習 SELECT 的語法會比我解釋還要來得好,你可以將我提供的語法與你的語法相互比對一下就可以了解了。

慢慢學將你所學習的過程記錄下來,下次就可以用得到了!!

我要發表回答

立即登入回答