[英]Mysql select match and unmatched records from two different tables by comparing more then two columns
id sys_id sys_date sys_load
-- ------ ---------- --------
1 4472 2017-09-06 500000
2 5678 2017-09-06 300000
3 4323 2017-09-06 400000
4 8976 2017-09-06 200000
5 8976 2017-09-06 0
6 9890 2017-09-06 0
7 9890 2017-09-06 100000
8 9999 2017-09-06 200000
9 4472 2017-09-05 100000
10 5678 2017-09-05 900000
id man_id man_date man_load
-- ------ ---------- --------
1 4472 2017-09-06 500000
2 5678 2017-09-06 300000
3 4323 2017-09-06 400000
4 8976 2017-09-06 200000
5 9890 2017-09-06 100000
1.我想通過將sys_id,sys_date,sys_load與man表man_id,man_date,man_load匹配來從系統表中選擇記錄。 日期來自前端。
select sys_id
, sys_load
from system
, man
where DATE(sys_date) = '2017-09-06'
and man_date = '2017-09-06'
and sys_id = man_id
and sys_load = man_load_amt
order
by sys_id;
給我如下所示的預期結果
1 4472 2017-09-06 500000
2 5678 2017-09-06 300000
3 4323 2017-09-06 400000
4 8976 2017-09-06 200000
5 9890 2017-09-06 100000
上面的查詢是好的還是錯的?
2.現在我想從系統表中選擇與上述日期為“ 2017-09-06”的結果集不匹配的記錄。 即
id sys_id sys_date sys_load
-- ------ ---------- --------
5 8976 2017-09-06 0
6 9890 2017-09-06 0
8 9999 2017-09-06 200000
注意:ID 8976和9890有兩個條目。 任何幫助將非常感激。
請擺脫舊的聯接。 請使用顯式聯接語法-
1-匹配記錄
select sys_id
,sys_load
from system
inner join man on sys_id = man_id
where DATE(sys_date) = '2017-09-06'
and man_date = '2017-09-06'
and sys_load = man_load_amt
order by sys_id;`
編輯- 我剛剛注意到您在系統中也有不匹配的記錄。 因此,您需要左聯接而不是內部聯接
2-對於不匹配的記錄
select sys_id
,sys_load
from system
left join man on sys_id = man_id
where DATE(sys_date) = '2017-09-06'
and (sys_load <> man_load or man_load is null)
order by sys_id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.