简体   繁体   中英

SQL Order By Column From another Table

$sql = "SELECT user2 FROM subscriptions WHERE user1 = '$username'";

This code works perfectly, but what I would like to do is ORDER it BY a column from my users table, the user_id column. Now I can't do this…

$sql = "SELECT user2 FROM subscriptions WHERE user1 = '$username' ORDER BY user_id";

Because there is no column called user_id in my subscriptions table, just in my users table.

I can't understand why you have two user columns, maybe it's a typo. But you need to JOIN the tables. In this case I've used a LEFT OUTER JOIN which will only return records from subscriptions and what matches the JOIN condition from users . ie user2 = user_id .

SELECT subscriptions.user2 
FROM subscriptions 
LEFT JOIN users ON subscriptions.user2 = users.username
WHERE subscriptions.user1 = '$username' 
ORDER BY users.user_id

You can select the user_id in your ORDER BY clause:

SELECT user2 
FROM subscriptions 
WHERE user1 = '$username' 
ORDER BY (select user_id from users where users.username = subscriptions.user2);

I surmise that users.username is unique, so you have two natural unique keys in your users table (user_id and username). You've decided to use username for references in other tables. That is okay.

If, however, users.username is not unique, then your databse design is broken and you should use the user_id as reference in other tables instead of username, of course.

您应该使用JOIN语法,然后您可以从users表中按user_id进行排序。

Use regular join (not LEFT JOIN) if you have one-to-one data relation.

SELECT a.user2 FROM subscriptions a, user b 
WHERE a.user2 = b.username
AND a.usera.user1 = '$username' ORDER BY b.user_id

This is hard to give working solution without viewing table's scheme. But from the query it's looks like you have poor dab design if you use '$username' to search in subscriptions instead of users table.

With an good database design your query should be like this:

SELECT a.fiel1, a.field2, a.user_id, b.field1, b.field2, b.user_id 
    FROM subscriptions a, user b 
    WHERE a.user_id = b.user_id
    AND b.username = '$username' ORDER BY b.user_id
  • Joins by user_id
  • Storing username once in users table
  • Use user_id in any other tables

你应该order by user_id desc使用order by user_id desc

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