0

谁能帮我处理这个 MySQL 查询?

SELECT p.ProductID, 
       p.StoreID, 
       p.DiscountPercentage 
 FROM Products p 
WHERE p.IsSpecial = 1 
  AND p.SpecialDate >= date_sub(now(),interval 15 minute) 
  AND p.DiscountPercentage >= ?DiscountPercentage 
  AND p.ProductID NOT IN (SELECT lf.LiveFeedID 
                            From LiveFeed lf 
                           WHERE p.ProductID = lf.ProductID 
                             AND lf.DateAdded >= date_sub(now(),interval 30 day)) 
  AND p.StoreID NOT IN (SELECT lf.LiveFeedID 
                          From LiveFeed lf 
                         WHERE p.StoreID = lf.StoreID 
                           AND lf.DateAdded >= date_sub(now(),interval 6 hour)) 
ORDER BY p.StoreID, p.DiscountPercentage DESC

我正在尝试加入过去 30 天内 ProductID 不在 livefeed 表中的位置,以及过去 6 小时内 storeid 不在 livefeed 表中的位置,但它似乎不起作用。知道我做错了什么吗?

4

2 回答 2

3

乍一看,您的第一个子查询似乎应该选择ProductID,而不是LiveFeedID您的第二个子查询应该选择StoreIDLiveFeedID

于 2009-11-23T06:04:39.643 回答
3

我来晚了:

  SELECT p.ProductID, 
         p.StoreID, 
         p.DiscountPercentage 
    FROM Products p 
   WHERE p.IsSpecial = 1 
     AND p.SpecialDate >= date_sub(now(),interval 15 minute) 
     AND p.DiscountPercentage >= ?DiscountPercentage 
     AND p.ProductID NOT IN (SELECT lf.productid
                               FROM LIVEFEED lf
                              WHERE lf.DateAdded >= DATE_SUB(NOW(), INTERVAL 30 DAY)) 
     AND p.storeid NOT IN (SELECT lf.storeid
                             FROM LIVEFEED lf
                            WHERE lf.DateAdded >= DATE_SUB(NOW(), INTERVAL 6 HOUR)) 
ORDER BY p.StoreID, p.DiscountPercentage DESC

您正在使用带有相关子查询的 EXISTS 语法...

我正在努力为每家商店获得最高折扣。

在这种情况下,请使用:

  SELECT p.StoreID, 
         MAX(p.DiscountPercentage)
    FROM Products p 
   WHERE p.IsSpecial = 1 
     AND p.SpecialDate >= date_sub(now(),interval 15 minute) 
     AND p.DiscountPercentage >= ?DiscountPercentage 
     AND p.ProductID NOT IN (SELECT lf.productid
                               FROM LIVEFEED lf
                              WHERE lf.DateAdded >= DATE_SUB(NOW(), INTERVAL 30 DAY)) 
     AND p.storeid NOT IN (SELECT lf.storeid
                             FROM LIVEFEED lf
                            WHERE lf.DateAdded >= DATE_SUB(NOW(), INTERVAL 6 HOUR)) 
GROUP BY p.storeid
ORDER BY p.StoreID, p.DiscountPercentage DESC
于 2009-11-23T06:12:31.343 回答