问题
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