比较2个表的数据

时间:2019-05-02 08:26:10

标签: mysql sql

我有2个表A和B,如下所示

表A

+---------+--------+
|  query  | status |
+---------+--------+
| number1 | solved |
+---------+--------+

表B

+----+---------+---------+
| id |  query  | status  |
+----+---------+---------+
|  1 | number1 | started |
|  2 | number1 | working |
|  3 | number1 | solved  |
+----+---------+---------+

如何检查表B的最新状态是否等于表A的状态

我尝试首先获取表2的最新状态,但我无法获得

select number ,max(status),max(id) 
from Table B 
group by number 
order by max(id) asc 

4 个答案:

答案 0 :(得分:0)

select *
from A a
    inner join B b on b.query = a.query
    inner join 
         (select max(id) id, query
          from B
          group by query) gq on gq.id = b.id and gq.query = b.query
where a.status = b.status

答案 1 :(得分:0)

这是一个简单的解决方案,它依赖于按ID排序并仅获得子查询的第一行。它只会返回两个表之间匹配的行。

SELECT a.* 
FROM tableA a
JOIN (SELECT query, status 
      FROM tableB
      ORDER BY ID desc 
      LIMIT 1) b ON a.query = b.query AND a.status = b.status

答案 2 :(得分:0)

使用联接和子查询

select a.* from
 tablea a join
(
select * from table_name t1
where id =( select max(id) from table_name t2 where t1.query=t2.query)
) b join on a.query=b.query and a.status=b.status

答案 3 :(得分:0)

类似

SELECT TA.query, TA.status AS current_status, TB.status AS Last_status, 
       (CASE WHEN TA.status=TB.status THEN 'OK' ELSE 'NOK' END) AS your_answer
FROM
TableA TA
INNER JOIN
    (
        SELECT query, MAX(ID) as max_id
        FROM TableB
        GROUP BY query
    ) TM ON TM.query=TA.query
INNER JOIN TableB TB ON TM.max_id = TB.id

仅当表B中的ID是某种递增的数字(最高=最后一行)时,