select rows which has latest date without repetition from two joined table?

时间:2015-10-06 08:54:43

标签: mysql

I have table A and B.

Table A has data like

|  id  |    status    | made at | ... |
|  1   |     new      |14-04-14 | ... |
|  2   |    fixed     |14-08-12 | ... |
|  3   |    fixed     |14-03-15 | ... |
| ...  |     ...      |  ..     | ... |

and in Table B,

|  id  |   A_id   |    changes   |changed at| ... |
|  1   |    1     |     new      | 14-04-14 | ... |
|  2   |    2     |     new      | 14-08-12 | ... |
|  3   |    2     |     fixed    | 14-08-28 | ... |
|  4   |    3     |     new      | 14-03-15 | ... |
|  5   |    3     |    fixed     | 14-05-11 | ... |
|  6   |    3     |    fixed     | 14-05-14 | ... |
|  ..  |   ..     |      ..      |   ..     | ... |

What I want as the result is to pick what has fixed status in table A and fixed changes in table B, with no repetition.

If it has same changes like 5 and 6 in B, I will pick only changed at latest data.

So the result will look like...

|  id  |  A_id   |  made at  |  status  |  changes  |  changed at |  ...  |
|  2   |   2     | 14-08-12  |  fixed   |   fixed   |  14-08-28   |  ...  |
|  3   |   3     | 14-03-15  |  fixed   |   fixed   |  14-05-14   |  ...  |

I tried select * from A, B where (A.status='fixed') and (A.id=B.A_id) and (B.changes='fixed') but still have repetition result in changes.

How can I make query right?

4 个答案:

答案 0 :(得分:0)

我认为您分享的示例输出不正确,ID列的值应为36,而不是23。无论如何试试这个

SELECT b3.id, a.id AS 'A_id', a.made_at AS 'made at', a.status, b3.changes, b3.changed_at AS 'changed at'
FROM
    a
    INNER JOIN (
        SELECT b1.id, b1.A_id, b1.changes, b1.changed_at FROM b AS b1 
        INNER JOIN 
        (SELECT A_id, MAX(changed_at) AS changed_at FROM b WHERE changes='fixed' GROUP BY 1) AS b2 ON b1.A_id=b2.A_id AND b1.changed_at=b2.changed_at
    ) b3 ON a.id=b3.A_id
WHERE
    a.status = 'fixed'

答案 1 :(得分:0)

尝试此查询

  SELECT tab.* FROM(SELECT A.*,B.A_id,B.chnages,B.changed at 
 FROM  A LEFT JOIN B ON A.id=B.A_id
 WHERE A.status='fixed' AND B.changes ='fixed' 
 ORDER BY B.changes_at DESC ) as tab GROUP BY tab.id 

答案 2 :(得分:0)

尝试此查询

SELECT
    a.id,
    b.A_id,
    a.status,
    a.made_at,
    b.changes,
    b.changed_at
FROM 
    A a
INNER JOIN
    B b ON b.A_id = a.id
WHERE
    a.status = 'fixed'      
    AND
    b.changes = 'fixed'
    AND 
    b.changed_at = (select 
                          MAX(b1.changed_at)
                        from 
                          b b1 
                        where 
                          b1.changes = b.changes 
                          and b1.A_id = b.A_id
                        )

答案 3 :(得分:-2)

试试这个

SELECT * FROM A 
LEFT JOIN 
    (SELECT * FROM B ORDER BY changed at DESC) AS tab ON a.id=tab.A_id
WHERE a.status='fixed' AND tab.changes='fixed'