当一个子句为false时,将查询设为true

时间:2013-07-26 09:58:02

标签: sql

这是我的查询

SELECT pl.NAME
  ,pl.id_product
  ,pl.link_rewrite
  ,i.id_image
  ,ar.id_auctions_rutcom
  ,ar.actual_bid_price
  ,ar.start_price
  ,ar.min_price
  ,ar.buy_now_price
  ,ar.finish_date
FROM ps_image i
  ,ps_auctions_rutcom ar
  ,ps_product_lang pl
WHERE ar.finish_date > '2013-07-26 11:18:15'
  AND ar.start_date < '2013-07-26 11:18:15'
  AND ar.active = 1
  AND ar.finish = 0
  AND pl.id_product = ar.id_product
  AND i.id_product = ar.id_product
  AND i.cover = 1
  AND pl.id_lang = 6

我在桌面上遇到问题ps_image没有图像i.id_product = ar.id_product我的查询返回false。如何更改查询设置为true?

3 个答案:

答案 0 :(得分:2)

您应该了解JOIN。谷歌吧。

您的查询等同于INNER JOIN

SELECT 
  pl.name, pl.id_product, pl.link_rewrite, i.id_image, ar.id_auctions_rutcom,
  ar.actual_bid_price, ar.start_price, ar.min_price, ar.buy_now_price, ar.finish_date 
FROM ps_auctions_rutcom ar
INNER JOIN ps_product_lang pl 
        ON pl.id_product = ar.id_product 
       AND pl.id_lang = 6
INNER JOIN ps_image i
        ON i.id_product = ar.id_product 
       AND i.cover = 1 
WHERE ar.finish_date > '2013-07-26 11:18:15' 
  AND ar.start_date < '2013-07-26 11:18:15' 
  AND ar.active = 1 
  AND ar.finish = 0 

使用INNER JOIN,如果相关表中没有匹配的行,则从结果集中省略该行。

现在,您应该使用OUTER JOIN,在这种情况下,行仍在结果集中,缺少的信息将设置为NULL

SELECT 
  pl.name, pl.id_product, pl.link_rewrite, i.id_image, ar.id_auctions_rutcom,
  ar.actual_bid_price, ar.start_price, ar.min_price, ar.buy_now_price, ar.finish_date 
FROM ps_auctions_rutcom ar
INNER JOIN ps_product_lang pl 
        ON pl.id_product = ar.id_product 
       AND pl.id_lang = 6
LEFT OUTER JOIN ps_image i
             ON i.id_product = ar.id_product 
            AND i.cover = 1 
WHERE ar.finish_date > '2013-07-26 11:18:15' 
  AND ar.start_date < '2013-07-26 11:18:15' 
  AND ar.active = 1 
  AND ar.finish = 0 

答案 1 :(得分:0)

您可以添加查询以确保ps_image不为空

i.id_product IS NOT NULL

答案 2 :(得分:0)

您应该将联接与过滤器分开,然后使用left join提供所有结果 无论图像是否存在

FROM ps_auctions_rutcom ar 
    left join
    ps_image i on i.id_product = ar.id_product 
         and i.cover = 1 
    left join
    ps_product_lang pl on pl.id_product = ar.id_product 
         and pl.id_lang = 6
WHERE ....