【问题标题】:Sort a table's query according to another table's value根据另一个表的值对表的查询进行排序
【发布时间】:2012-10-10 21:48:17
【问题描述】:
这是场景:
我想根据 table2 中的年龄对 table1 中的名称进行排序。 SQL 查询是什么?
表1
ID | Name
---|-----
1 | Jack
2 | Tony
3 | John
这是table2
ID | Age
---|-----
1 | 17
2 | 18
3 | 15
两个表都与ID字段相关。
【问题讨论】:
标签:
mysql
sql
sql-order-by
jointable
【解决方案1】:
select t1.id, t1.name, t2.age
from table1 t1 join table2 t2 on t1.id=t2.id
order by t2.age
【解决方案2】:
您需要加入两个表,然后您可以通过table2.Age订购
SELECT t1.*
FROM table1 t1
JOIN Table2 t2
ON t1.ID = t2.ID
ORDER BY Age
See this SQLFiddle
【解决方案3】:
假设 ID 字段是两个表的 JOIN 列并考虑到列的用途,理想情况下它们应该在一个表中,因为它们具有一一对应关系。
如果您的示例不适合您的问题,那么您将编写一个查询来 JOIN 两个表,仅选择感兴趣的列(从一个或两个表中)并从适当的表中对列进行排序。