how to fix mysql error number #1250 Table 'a1' from one of the SELECTs cannot be used in field list?

拟墨画扇 提交于 2021-02-08 04:41:07

问题


I am doing following way to sorting data by date and time

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

here my table structure I get mysql error number #1250 Table 'a1' from one of the SELECTs cannot be used in field list

how to sorting data with unioun clause correctly as my case?


回答1:


You can try below - you need to use order by clause in outer query

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



回答2:


If not otherwise specified, column names in result will be determined by first query of union. Hence, this query should do what you want:

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;


来源:https://stackoverflow.com/questions/53809027/how-to-fix-mysql-error-number-1250-table-a1-from-one-of-the-selects-cannot-be

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!