左边连接由max和group连接多个值

时间:2018-02-20 10:10:39

标签: sql

在下面的查询中,我想连接两个表,因此我有最新的时间戳和table_b的状态(不是每个状态的最新时间戳,当前发生)。你可以建议,我如何重写我的查询而不是这个(我省略了不必要的字段)

id           timestamp           status
7683295      1518621510130       "pending"
7683295      1518625048458       "unmatched"

它返回此

id           timestamp           status
7683295      1518625048458       "unmatched"

查询本身

SELECT
    table_a.id,
    COALESCE(table_b.status, 'new'),
    table_a.description,
    table_a.title,
    table_a.category,
    table_a.not_approved_timestamp,
    table_b.timestamp
FROM [table_a_location] AS table_a
LEFT JOIN (
    SELECT id, status, max(timestamp) AS timestamp
    FROM [table_b_location]
    GROUP BY id, status) as table_b
ON table_a.id == table_b.id
WHERE (table_a.approved_market_sku_id IS NULL AND table_b.status NOT IN ('pending'))
OR (table_a.not_approved_timestamp > table_a.approved_timestamp AND table_b.status NOT IN ('pending', 'unmatched'))

LIMIT 100

谢谢!

1 个答案:

答案 0 :(得分:0)

首先,您的where子句将外连接转换为内连接,因此使用left join会产生误导。

您的问题是您为每个状态获取单独的行。我假设你只想要最新的一个,所以这个FROM子句可能会解决你的问题:

FROM [table_a_location] table_a JOIN
     (SELECT id, max(timestamp) AS timestamp
      FROM [table_b_location]
      GROUP BY id
     ) max_table_b
     ON table_a.id = max_table_b.id JOIN
     table_b_location table_b
     ON max_table_b.id = table_b.id AND max_table_b.timestamp = table_b.timestamp