-1

I have two tables of which one is updated daily. I would like to display "only" the latest record for each row.

This is the query I am using now that of course returns all the records.

SELECT * 
FROM ss_pumps, secondary_systems WHERE ss_pumps.id=secondary_systems.segment_id 
ORDER BY id ASC

Any help would be greatly appreciated!

4

3 回答 3

3

You can find the latest record for every segment_id by ID using subquery. The result of the subquery is then join against the two tables: ss_pumps and secondary_systems.

SELECT  a.*, c.* 
FROM    ss_pumps a
        INNER JOIN 
        (
            SELECT  segment_id, MAX(datefield) max_val
            FROM    secondary_systems
            GROUP   BY segment_id
        )b ON a.id = b.segment_id
        INNER JOIN secondary_systems c
            ON  b.segment_id = c.segment_id AND
                b.max_val = c.datefield

Actually, I'm not sure how your tables: ss_pumps and secondary_systems are related with each other.

I think you want it the other ways,

SELECT  a.*, b.*
FROM    secondary_systems a
        INNER JOIN ss_pumps b
            ON a.segment_ID = b.segment
        INNER JOIN
        (
            SELECT  segment, MAX(ID) max_val
            FROM    ss_pumps
            GROUP   BY segment
        ) c ON  b.segment = c.segment AND
                b.ID = c.max_val
于 2013-02-04T14:18:26.677 回答
1

Use this query:

SELECT * FROM ss_pumps, secondary_systems WHERE ss_pumps.id=secondary_systems.segment_id ORDER BY id DESC LIMIT 1

This is assuming that id is an auto increment column and will always be inserted in order.

于 2013-02-04T14:16:16.227 回答
-2

Here's what I got:

SELECT * 
FROM
    ss_pumps ssp
    LEFT JOIN ( SELECT * FROM secondary_systems ORDER BY id DESC ) ss ON ( ssp.id = ss.segment_id )
GROUP BY
    ssp.id
ORDER BY
    ssp.id ASC

CAVEAT: I'm assuming that the secondary_systems has its own id field that also autoincrements. That's the only way you can make sure you're getting "only" the latest record for each row.


Demo: http://sqlfiddle.com/#!2/f816b/2/0

In my demo ss_pumps held the parents while secondary_systems held the children. Each parent has 3 children. All but the last children are boys. The last child is always a girl. According to your problem, the resulting query should yield only girls.

| ID | PARENT | SEGMENT_ID | CHILD |
------------------------------------
|  1 | mother |          1 | betty |
|  2 | father |          2 |  tina |
于 2013-02-04T14:44:49.307 回答