union all 和where条件一起使用查询数据不对的问题

来源:互联网 发布:linux改用户名命令 编辑:程序博客网 时间:2024/06/12 21:38

最近写sql的时候,需要两张表结合一起查询数据,并且根据条件从查询到的数据中只取一条,结果没有取到数据。

表一 test1

id name 1 张三 2 李四 3 王五

表二 test2

id name 4 小一 5 小二 6 小三

查询语句是这样的:

 select id ,name from test1  union  select id, name from test 2  where id = 4limit 1

这个sql的目的是,从两张表中,取出id = 4 的数据,如果有多条,只取一条。

但是查询结果是:

id name 1 张三

经过分析发现,这条sql等效于下面:

select id ,name from test1  union ( select id, name from test 2  where id = 4 )limit 1

这条sql(下面这个),查询结果是:

select id ,name from test1  union ( select id, name from test 2  where id = 4 )
id name 1 张三 2 李四 3 王五 4 小一

然后limit 1, 取出来的就是第一条,即张三-1

所以这条sql应该修改成下面:

第一种修改方式:

select id ,name from test1 where id = 4  union  select id, name from test 2  where id = 4 limit 1

第二种修改方式:

select t.* from (select id ,name from test1  union  select id, name from test 2  ) t where t.id = 4 limit 1

这两种修改方式都能正确查询到结果。

记录一下,防止后面再犯这种错误。

阅读全文
0 0
原创粉丝点击