mysql查询union_mysql查询两个表,UNION和where子句

bd96500e110b49cbb3cd949968f18be7.png

I have two tables.

I query like this:

SELECT * FROM (

Select requester_name,receiver_name from poem_authors_follow_requests as one

UNION

Select requester_name,receiver_name from poem_authors_friend_requests as two

) as u

where (LOWER(requester_name)=LOWER('user1') or LOWER(receiver_name)=LOWER('user1'))

I am using UNION because i want to get distinct values for each user if a user exists in the first table and in the second.

For example:

table1

nameofuser

peter

table2

nameofuser

peter

if peter is on either table i should get the name one time because it exists on both tables.

Still i get one row from first table and a second from table number two. What is wrong?

Any help appreciated.

解决方案

There are two problems with your SQL:

(THis is not the question, but should be considered) by using WHERE over the UNION instead of the tables, you create a performance nightmare: MySQL will create a temporary table containing the UNION, then query it over the WHERE. Using a calculation on a field (LOWER(requester_name)) makes this even worse.

The reason you get two rows is, that UNION DISTINCT will only suppress real duplicates, so the tuple (someuser,peter) and the tuple (someotheruser, peter) will result in duplication.

Edit

To make (someuser, peter) a duplicate of (peter, someuser) you could use:

SELECT

IF(requester_name='peter', receiver_name, requester_name) AS otheruser

FROM

...

UNION

SELECT

IF(requester_name='peter', receiver_name, requester_name) AS otheruser

FROM

...

So you only select someuser which you already know : peter

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值