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

时间:2017-10-17 12:12:07

标签: mysql

系统表

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 table 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

注意:ids 8976和9890有两个条目。任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:0)

请摆脱旧式联接。请使用显式连接语法 -

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;