简体   繁体   English

MySQL通过比较两个以上的列从两个不同的表中选择匹配和不匹配的记录

[英]Mysql select match and unmatched records from two different tables by comparing more then two columns

system Table 系统表

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

man Table 人表

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.I want to select records from system table by matching sys_id,sys_date,sys_load with man table man_id,man_date,man_load. 1.我想通过将sys_id,sys_date,sys_load与man表man_id,man_date,man_load匹配来从系统表中选择记录。 date comes from front end. 日期来自前端。

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; 

gives me the expected result like below 给我如下所示的预期结果

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

is the above query is good or any wrong in it? 上面的查询是好的还是错的?

2.Now i want to select the records from system table which are not matching with the above result set for the date '2017-09-06'. 2.现在我想从系统表中选择与上述日期为“ 2017-09-06”的结果集不匹配的记录。 ie,

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

note: ids 8976 and 9890 have two entries. 注意:ID 8976和9890有两个条目。 any help would be really appreciated. 任何帮助将非常感激。

Please get rid of old styled joins. 请摆脱旧的联接。 Please use explicit join syntax - 请使用显式联接语法-

1 - For matching records 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;`

Edit - I have just noticed you have unmatched records in system also. 编辑- 我刚刚注意到您在系统中也有不匹配的记录。 So you need left join rather than inner 因此,您需要左联接而不是内部联接

2 - For un-matching records 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM