MySQL - Order by values in separate table

这一生的挚爱 提交于 2019-12-12 00:25:00

问题


I have two MySQL tables. Table1:

id name otherid

Table2:

id otherid time

In each table, the "id" is a unique identifier for every row (and is also the primary key) the "otherids" correspond between tables. There may be several (or 0) rows in table2 that have an otherid that corresponds to an otherid in table1. Table

For example, Table 1:

id name otherid
1  bob  24
2  joe  326

Table 2:

id otherid time
4  326     2014-03-12 023:38:59
5  24      2013-02-11 22:05:21
6  24      2013-02-10 13:27:58

I am looking to fetch every row in table1, ordered by the most recent time of the rows in table2 that go with it according to the otherid. In my example, this is the result I would be looking for:

id name time
2  joe  2014-03-12 023:38:59
1  bob  2013-02-11 22:05:21

This is because Joe has the most recent time from table2.


回答1:


See below example :

SELECT table1.*, max(table2.time) 
FROM table1 
INNER JOIN table2 ON table1.otherid = table2.otherid
GROUP BY table2.otherid
ORDER BY table2.id

See SqlFiddle Demo




回答2:


Try

SELECT MIN(a.id) AS `id`, MIN(a.name) AS `name`, MAX(b.time) AS `time`
FROM table1 a INNER JOIN
     table2 b ON a.otherid = b.otherid
GROUP BY a.otherid
ORDER BY b.time DESC

Working sqlfiddle




回答3:


you can use MAX function for get most recent time.

ex. MAX(time)




回答4:


SELECT
    Table1.id, name, MAX(time)
FROM
    Table1
    JOIN Table2 USING (otherid)
GROUP BY
    otherid
ORDER BY
    time DESC



回答5:


SELECT DISTINCT(table1.id),table1.name,table2.time FROM table1 
LEFT JOIN table2 ON table1.otherid=table2.otherid
ORDER BY table2.time DESC;



回答6:


You can try this with a join and subquery:

select id, name
from tb1 a
left join
(select otherid, max(dt) mdt
from tb2
group by otherid) b
on a.otherid = b.otherid
order by b.mdt desc
;


来源:https://stackoverflow.com/questions/14825309/mysql-order-by-values-in-separate-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!