简体   繁体   中英

Get all record from one table plus the relative last record of a second table

Situation (simplified):

tableA

id  | id_device
----+----------
... | 10
... | 11
... | 12

tableB

id  | id_device | val
----+-----------+----
... | 10        | 200
... | 10        | 105
... | 10        | 120
... | 11        | 80

Result expected: All the records from tableA , and for each record of tableA , the last relative record on tableB .

id_device | val 
----------+-----
10        | 120
11        | 80
12        | null

I tried to something like this, but I can't get the last record correctly:

SELECT tableA.*,
       tableB.* 
FROM tableA
LEFT JOIN (
    SELECT id_device,
           val,
           MAX(id) 
    FROM tableB
    GROUP BY id_device
) AS tableB
     ON tableA.id_device = tableB.id_device

Your subquery is selecting the MAX(d) from tableB , and undetermined values for id_device and val . It's not selecting the entire record when MAX(id) . To do so, you need to select the MAX(id) and then join based on it. You can achieve that by using simple descending order and pick the top row:

SELECT tableA.id_device, tableB.val
FROM tableA
LEFT JOIN tableB ON tableB.id = (SELECT id
                                 FROM tableB
                                 WHERE tableA.id_device = tableB.id_device
                                 ORDER BY id DESC
                                 LIMIT 1)

This allows you to select several fields from tableB , but if you're only interested in a single field like val , you can also select it directly from the subquery instead of joining on it:

SELECT tableA.id_device, (SELECT val
                          FROM tableB
                          WHERE tableA.id_device = tableB.id_device
                          ORDER BY id DESC
                          LIMIT 1) AS val
FROM tableA

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