简体   繁体   中英

How to use ORDER BY FIELD with subquery in MySQL?

Suppose there are two tables. First table, 'user_actions', has two fields: 'user_id' and 'action'. Second table, 'users', also has two fields: 'id' and 'name'. I want to sort the first table so that actions commited by users Aaron or Bruce go first and actions commited by Yuriy and Zorro go last. How would I do that?

I tried this:

select * from `user_actions` order by field(`user_id`,(select distinct `id` from `users` order by `name`))

Doesn't work.

select ua.user_id, ua.action, u.name from user_actions ua
inner join users u on u.user_id = ua.user_id
order by u.name

Why the subquery and not a join?

Something like this:

select ua.*
from user_actions ua inner join users u on ua.user_id = u.id
order by u.name

How about

select user_id,action from user_actions join users 
  on user_actions.user_id = users.id 
  order by name

You can try:

SELECT u1.user_id, u1.action, u2.name FROM user_actions u1, users u2
WHERE u1.user_id=u2.id 
ORDER BY u2.name 

i suppose this query would suffice

SELECT * FROM user_actions ORDER BY name

Order by keyword by default sorts in ascending, so wont need ASC after the 'name' field. If you want the opposite way just add DESC after 'name'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM