如何联接两个mysql表并从联接表中检索最新结果?

时间:2018-07-30 10:57:17

标签: mysql

我有两个桌子。我需要加入这两个表并从执行表中检索最新状态。我该如何找回?

我的架构和数据:

CREATE TABLE test 
    (`id` serial primary key, `ref_id` int, `ref_name` varchar(7))
;

INSERT INTO test 
    (`id`, `ref_id`, `ref_name`)
VALUES
    (1, 1, 'trial'),
    (2, 3, 'test'),
    (3, 7, 'testing')
;


CREATE TABLE execution 
    (`id` serial primary key, `ref_id` int, `status` varchar(11))
;

INSERT INTO execution 
    (`id`, `ref_id`, `status`)
VALUES
    (1, 1, 'Completed'),
    (2, 2, 'Completed'),
    (3, 1, 'Completed'),
    (4, 3, 'In progress'),
    (5, 3, 'To do'),
    (6, 2, 'In progress'),
    (7, 1, 'Completed'),
    (7, 1, 'To do')
;

预期结果如下。

ref_id | ref_name | status      |
3      | testing  | In progress |
2      | test     | To do       |
1      | trial    | To do       |

我尝试过以下查询:

SELECT
    ref_id, 
    ref_name, 
    status 
FROM 
    test 
    JOIN execution ON test.ref_id = execution.ref_id 
GROUP BY `ref_id` 
ORDER BY `ref_id` DESC;

此查询检索status,但检索到的status不是最新的。如何通过加入这两个表来检索最新状态。

2 个答案:

答案 0 :(得分:0)

您可以使用以下查询

select T2.ref_id,T2.ref_name,OE.status from
   (
   select t1.ref_id,t1.ref_name,e.id from test t1 inner join

    (select max(id) as id,ref_id  from execution group by ref_id) as e
    on
    t1.ref_id=e.ref_id
   ) as T2
inner join execution OE on T2.id=OE.id

https://www.db-fiddle.com/f/rvnm8APX27dmW9a84JkCsS/1

答案 1 :(得分:0)

似乎您提供了不正确的数据作为示例,因为ref_id 7在以下位置找不到 执行表。但这可能对您有帮助

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="target1" class="col-sm-4 hide">
    Hello my name is col-sm-4! for display:none !important;
</div>

<div id="target2" class="col-sm-4 display-none">
    Hello my name is col-sm-4! for display:none;
</div>

<input type="button" class="button" value="show col-sm-4" id="button1">
<input type="button" class="button" value="show col-sm-4" id="button2">