没有 except 的 mysql,实现 except 的途径分析

2018-03-29 14:46:19 +08:00
 jahan

select * from (

select count(*) as cnt ,all columns ( select distinct * from table1
union all
select distinct * from table2 ) group by all columns ) where cnt =1

想把在在 db2 中,要想知道在 table1 而不再 table2 中的数据,可以 select * from table1 except select * from table2 可是现在在 mysql 下面 except 没有,用这个 select * from (

select  count(*) as cnt  ,all columns 
(
select distinct * from table1    
 union all  
select distinct * from table2
)
group by all columns 
) where cnt =1 

一直报错,也没查到 all columns 的用法。

7858 次点击
所在节点    MySQL
10 条回复
b821025551b
2018-03-29 15:08:53 +08:00
用 table1 left join table2 就行了。
jahan
2018-03-29 15:14:53 +08:00
@b821025551b 主要是没有一个字段可以把两个记录区分开,只有全字段内容相同的列才不要了。

left jion 都要有个 on,这个 on 的话,就没办法写了。
jahan
2018-03-29 15:17:05 +08:00
@b821025551b 这 2 表没有 pk,只是一堆字符串和数字。让我 on 的无从下手
b821025551b
2018-03-29 15:22:30 +08:00
test1:
id | value
1 |A
2 |B
3 |C

test2:
id | value
1 |A
2 |B
3 |D

select test1.* from test1 left join test2 on test1.value=test2.value where test2.value is null

result:
id | value
3 |C

和 pk 没关系吧,on 在你要比对的字段上并且 where 限定右表那个字段是 null 就可以了。
jahan
2018-03-29 16:29:29 +08:00
那要全字段比较了,我试试
jahan
2018-03-29 16:54:08 +08:00
select * from (
select count(*) as cnt ,id,value
(
select distinct * from table1
union all
select distinct * from table2
)
group by id,value
) where cnt =1

这种就一直报错,想不出哪里有问题
wqzjk393
2018-03-29 19:35:00 +08:00
@jahan 少个 from …
jahan
2018-03-29 19:50:02 +08:00
@wqzjk393 这个有了,一直报每个表都需要别名。可是
select a.* from (
select count(*) as cnt ,id,value
(
select distinct * from table1 a
union all
select distinct * from table2 b
)
group by a.id,a.value
) where a.cnt =1

??
wqzjk393
2018-03-29 20:25:54 +08:00
from
(
select distinct * from table1 a
union all
select distinct * from table2 b
)
这里,应该是把 union 当成子查询的表了,而根据规定所有子查询的表都要有别名。 另外一点,能不用*查询就别用*,经常出一些奇奇怪怪的错误,而且在工程上基本上老大都不允许这么查
choulinlin
2018-03-29 20:32:54 +08:00
where not exists ?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/442495

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX