sql错误order by子句不起作用

lfapxunr  于 2021-06-25  发布在  Mysql
关注(0)|答案(3)|浏览(332)

order by子句不使用union,别名(as)出现错误
信使表

mid    senderid   receiverid   message   
      ---------------------------------------
        4       100       200          hi
        3       200       100          hello
        2       100       200          hi
        1       100       200          hi

select语句

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'

我不知道我犯了什么错误,帮我提前谢谢

yks3o0rb

yks3o0rb1#

联合查询中没有中间字段,所以

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
jvidinwx

jvidinwx2#

在你的联队成绩中你没有中锋
你只有 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
lnvxswe2

lnvxswe23#

你为什么用这个 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;

相关问题