0

2 つの MySQL テーブルがあります。表1:

id name otherid

表 2:

id otherid time

各テーブルでは、「id」はすべての行の一意の識別子です (また、主キーでもあります)。「otherids」はテーブル間で対応します。table2 には、table1 の otherid に対応する otherid を持つ行がいくつか (または 0) ある場合があります。テーブル

たとえば、表 1:

id name otherid
1  bob  24
2  joe  326

表 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

私は、table1 のすべての行を取得しようとしています。これは、otherid に従って、table2 の行の最新の時間順に並べられています。私の例では、これは私が探している結果です:

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

これは、Joe が table2 から最新の時間を取得しているためです。

4

6 に答える 6

2

以下の例を参照してください。

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

SqlFiddle のデモを見る

于 2013-02-12T04:25:30.060 に答える
1

試す

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

ワーキングsqlfiddle

于 2013-02-12T04:34:05.583 に答える
0

これは、結合とサブクエリで試すことができます。

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
;
于 2013-02-12T04:39:43.490 に答える
0
SELECT
    Table1.id, name, MAX(time)
FROM
    Table1
    JOIN Table2 USING (otherid)
GROUP BY
    otherid
ORDER BY
    time DESC
于 2013-02-12T04:25:50.130 に答える
0

関数を使用MAXして最新の時間を取得できます。

元。MAX(time)

于 2013-02-12T04:25:25.390 に答える
0
SELECT DISTINCT(table1.id),table1.name,table2.time FROM table1 
LEFT JOIN table2 ON table1.otherid=table2.otherid
ORDER BY table2.time DESC;
于 2013-02-12T04:32:56.740 に答える