ORDER BY子句不使用Union,别名(as)得到一些错误
Messenger表
mid senderid receiverid message
---------------------------------------
4 100 200 hi
3 200 100 hello
2 100 200 hi
1 100 200 hi
选择语句
select senderid as new_id from messenger where receiverid=200
union
select receiverid from messenger where senderid =200
order by mid desc
错误
#1054 - Unknown column 'mid' in 'order clause'
我不知道我犯了什么错误,请提前谢谢你
答案 0 :(得分:2)
在你的联合结果中,你没有中间栏
你只有new_id
你应该添加
select mid, senderid as new_id
from messenger where receiverid=200
union
select mid, receiverid
from messenger where senderid =200
order by mid desc
或仅使用单个查询避免联合
select case when senderid = 200 then reciverid else senderid as new_id
from messenger
where receiverid=200 or senderid = 200
order by mid
答案 1 :(得分:1)
您为什么使用union
?
select (case when receiverid = 200 then senderid else receiverid end) as new_id
from messenger m
where 200 in (receiverid, senderid)
group by new_id
order by min(mid) desc;
答案 2 :(得分:0)
您的联合查询中没有中间字段,因此要么将其设为
select senderid as new_id from messenger where receiverid=200
union
select receiverid as new_id from messenger where senderid =200
order by new_id desc
或
select mid,senderid as new_id from messenger where receiverid=200
union
select mid,receiverid as new_id from messenger where senderid =200
order by mid desc