仅获取与间隔匹配的唯一带时间戳的行

时间:2016-02-19 01:21:08

标签: mysql

我有这两张桌子......

产品:

id product_id store_id
1  242234     54034
2  224222     83820
3  839202     24224
4  939284     54034

定价:

product_id last_update          source
242234     2016-02-11 12:00:00  7
242234     2016-02-12 12:00:00  7
242234     2016-02-13 12:00:00  7
839202     2016-02-14 12:00:00  3
839202     2016-02-15 12:00:00  3
839202     2016-02-16 12:00:00  3
939284     2016-01-08 12:00:00  7
939284     2016-02-15 12:00:00  7
939284     2016-02-16 12:00:00  7

我想只获取products.id只有pricing.last_update超过3天的pricing.last_update个值。如果pricing.product_id的定价表中有一行有更新的更新,那么我想完全忽略该pricing.product_id

为此,我尝试过这个查询,但它仍然会返回包含较新条目的ID:

SELECT
    pps.id
FROM
    pricing pr
JOIN
    products pps
        ON pps.product_id = pr.product_id
WHERE
    pr.source = 7 AND
    pps.store_id = 54034
GROUP BY
    pps.id
HAVING
    pr.last_update < NOW() - INTERVAL 3 DAY
ORDER BY
    pr.last_update DESC;

从给出的示例中,它应该只返回pps.id = 242234,而是返回939284

我如何构建我的查询?

1 个答案:

答案 0 :(得分:1)

您可以使用相关not exists子查询来查找没有任何定价数据超过3天的产品;像这样:

SELECT DISTINCT
  pps.product_id
FROM
  pricing pr
JOIN
  products pps
        ON pps.product_id = pr.product_id
WHERE
    pr.source = 7 
    AND
    pps.store_id = 54034
    AND NOT EXISTS
    (
       SELECT 1 FROM pricing 
       WHERE pps.product_id = product_id
       AND last_update >= NOW() - INTERVAL 3 DAY
    )
ORDER BY
    pr.last_update DESC;

Sample SQL Fiddle

根据您的示例数据,此查询将仅返回pps.id = 242234