左连接将排除某些行

时间:2014-03-24 06:33:26

标签: mysql sql

当我离开加入下表时,我得到了所有id的结果。我需要排除sms表中没有单个id的结果。 所以预期的产出如下:

+-----------+-----------+
| messageid | mobilenos |
+-----------+-----------+
| a         |        12 |
| c         |        31 |
+-----------+-----------+
2 rows in set (0.00 sec)

消息“d”不应显示在输出中,因为短信表中没有“d”的单个条目。

我想知道以下查询是否正确或是否有更好的方法:

select a.* from splitvalues as a 
left join sms as b on a.messageid = b.batchid and a.mobilenos = b.destination 
left join (select a.messageid from splitvalues as a left join sms as b on a.messageid = b.batchid  where b.batchid is null) as dt on dt.messageid = a.messageid where dt.messageid is null and b.destination is null;

以下是表格详情:

splitvalues
messageid mobilenos
a 10
a 11
a 12
b 20
b 21
b 22
b 23
b 24
c 30
c 31
d 40
d 41
d 42
d 43

sms
batchid destination
a 10
a 11
b 20
b 21
b 22
b 23
b 24
c 30

drop table if exists splitvalues;
drop table if exists sms;

create table if not exists splitvalues (messageid varchar(255), mobilenos int);
create table if not exists sms (batchid varchar(255), destination int);
insert into splitvalues values ('a', 10), ('a', 11), ('a', 12), ('b', 20), ('b', 21), ('b', 22), ('b', 23), ('b', 24), ('c', 30), ('c', 31), ('d', 40), ('d', 41), ('d', 42), ('d', 43);

insert into sms values ('a', 10), ('a', 11), ('b', 20), ('b', 21), ('b', 22), ('b', 23), ('b', 24), ('c', 30);

mysql> select a.* from splitvalues as a left join sms as b on a.messageid = b.batchid and a.mobilenos = b.destination where b.destination is null;
+-----------+-----------+
| messageid | mobilenos |
+-----------+-----------+
| a         |        12 |
| c         |        31 |
| d         |        40 |
| d         |        41 |
| d         |        42 |
| d         |        43 |
+-----------+-----------+
6 rows in set (0.00 sec)

3 个答案:

答案 0 :(得分:0)

试试这个...

从[dbo]中选择一个。*。[splitvalues] a.messageid = b.batchid

中的连接[dbo]。[sms] b

或者

从[dbo]中选择一个。*。[splitvalues] a,[dbo]。[sms] b其中a.messageid = b.batchid

答案 1 :(得分:-2)

尝试内部联接,它将生成两个表中都存在的行

select * from splitvalues as a
inner join sms as b on a.messageid = b.batchid and a.mobilenos = b.destination 

答案 2 :(得分:-2)

select * from
splitvalues
where mobilenos not in(select destination from sms) limit 2;