如何在MYSQL中设置其他表按ID排序

时间:2017-01-04 05:28:46

标签: mysql

我有两张桌子,下面给出的图片。

  

tb_user

enter user table

  

tb_user_connection

enter image description here

select * from tb_user_connection WHERE connection_type='a' 
AND user_id = '1' AND user_id <= connection_id
union all
select *
from tb_user_connection t
where user_id > connection_id 
and connection_type='a' and not exists (
select 1
from tb_user_connection t1
where t1.user_id = t.connection_id
and t1.connection_id = t.user_id 
)
  

所以,我想从tb_user_connection获取记录,但是依次排序   tb_user.first_name那么,我怎么设置这个查询?

1 个答案:

答案 0 :(得分:1)

SELECT  * 
FROM 
    (select *,(select first_name fron tb_user where tb_user.id =tb_user_connection.user_id) as first_name_my from tb_user_connection WHERE connection_type='a' 
AND user_id = '1' AND user_id <= connection_id
union all
select *,(select first_name fron tb_user where tb_user.id=t.user_id) as first_name_my
from tb_user_connection t
where user_id > connection_id 
and connection_type='a' and not exists (
select 1
from tb_user_connection t1
where t1.user_id = t.connection_id
and t1.connection_id = t.user_id 
)) dum
ORDER   BY first_name_my

尝试使用此查询。