我在这个问题上挠了很久,不知道如何解决。
我有2个mysql表
表1
+----+----------------------+
| id | name | order_list |
+----+----------------------+
| 1 | Bob | 3 |
| 2 | Marc | 2 |
| 3 | Edith | 1 |
| 4 | John | 4 |
+----+----------------------+
表2
+----+-------------------+
| id | user_id | sale |
+----+-------------------+
| 1 | 3 | 30 |
| 2 | 2 | 40 |
| 3 | 1 | 100 |
| 4 | 3 | 75 |
| 5 | 2 | 40 |
| 6 | 1 | 100 |
| 7 | 4 | 75 |
+----+-------------------+
我需要从表 2 中进行所有购买,并按表 1 中的 order_list 和表 2 中的 user_id 进行排序。
现在我正在 PHP 中这样做。 1 个查询,通过 order_list 从表 1 order 中获取员工 ID。 一个循环 每个员工在 1 个查询中获得销售
我需要每次销售都是独立的,而不是求和或分组。
query to get the id from table 1 order by order_list
loop
query the table2 for the sale of the looped employee
end loop
我知道这可以通过类似的事情来完成。
SELECT * FROM table2 ORDER BY FIELD (id,order from table 1)
最佳答案
基本的加入
就足够了:
select t2.*
from table2 t2 join
table1 t1
on t2.user_id = t1.id
order by t1.order_list;
或者,如果您愿意,可以在 order by
中放置一个子查询:
select t2.*
from table2 t2
order by (select t1.order_list from table1 t1 where t1.id = t2.user_id);
关于MYSQL ORDER BY 字段来自列表和其他表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44402211/