如何修复mysql错误号#1250表'a1'中的一个selects不能在字段列表中使用?

3xiyfsfu  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(496)

我正在按日期和时间对数据进行排序

select b.app_user_id,b.username,a.message_content,a.message_to,a.message_date 
from app_messages a 
left join app_users b 
on a.message_from = b.app_user_id
where a.message_to=1 and b.app_user_id= 4
UNION 
select b1.app_user_id,b1.username,a1.message_content,a1.message_to,a1.message_date 
from app_messages a1 
left join app_users b1 
on a1.message_from = b1.app_user_id 
where a1.message_to=4 and b.app_user_id= 1 
order by a1.message_date,a.message_date

这是我的table结构


我得到mysql错误号#1250表'a1'从一个选择不能在字段列表中使用
如何用unioun子句正确排序数据?

eqfvzcg8

eqfvzcg81#

如果没有另外指定,结果中的列名将由union的第一个查询确定。因此,此查询应该满足您的要求:

select b.app_user_id,b.username,a.message_content,a.message_to,a.message_date 
from app_messages a 
left join app_users b 
on a.message_from = b.app_user_id
where a.message_to=1 and b.app_user_id= 4
UNION 
select b1.app_user_id,b1.username,a1.message_content,a1.message_to,a1.message_date 
from app_messages a1 
left join app_users b1 
on a1.message_from = b1.app_user_id 
where a1.message_to=4 and b.app_user_id= 1 
order by message_date;
bfnvny8b

bfnvny8b2#

您可以在下面尝试-您需要在外部查询中使用ORDERBY子句

select * from
(
select b.app_user_id,b.username,a.message_content,a.message_to,a.message_date 
from app_messages a 
left join app_users b 
on a.message_from = b.app_user_id
where a.message_to=1 and b.app_user_id= 4
UNION 
select b1.app_user_id,b1.username,a1.message_content,a1.message_to,a1.message_date 
from app_messages a1 
left join app_users b1 
on a1.message_from = b1.app_user_id 
where a1.message_to=4 and b1.app_user_id= 1 
)A order by message_date

相关问题