为什么当包含这两个字段时,此SQL不起作用

时间:2013-04-30 03:12:25

标签: mysql sql

所以这第一个SQL返回零行:

SELECT b.b_id 
FROM `buy` b 
    INNER JOIN `buy_multiples` AS bm 
        ON b.b_id = bm.b_id 
        AND b.buy_status IN (2)  
WHERE bm.`option_type` = 'area_id'  
AND bm.selected_option_key IN (10)
AND bm.`option_type` = 'bzips'  
AND bm.selected_option_key IN (37027)
GROUP BY b.b_id 

第二个SQL返回b_id 5024和4987:

SELECT b.b_id 
FROM `buy` b 
    INNER JOIN `buy_multiples` AS bm 
        ON b.b_id = bm.b_id 
        AND b.buy_status IN (2)  
WHERE bm.`option_type` = 'bzips'  
AND bm.selected_option_key IN (37027)
GROUP BY b.b_id 

第三个SQL返回b_id 5024和4987和4989:

SELECT b.b_id 
FROM `buy` b 
    INNER JOIN `buy_multiples` AS bm 
        ON b.b_id = bm.b_id 
        AND b.buy_status IN (2)  
WHERE bm.`option_type` = 'area_id'  
AND bm.selected_option_key IN (10)
GROUP BY b.b_id 

为什么第一个返回零行?

2 个答案:

答案 0 :(得分:1)

在第一个查询中,您正在查找bm.option_type = 'area_id'的任何记录 和bm.option_type = 'bzips'。这将始终返回0结果。你想使用:

SELECT b.b_id 
FROM `buy` b 
    INNER JOIN `buy_multiples` AS bm 
        ON b.b_id = bm.b_id 
        AND b.buy_status IN (2)  
WHERE bm.`option_type` = 'area_id'  
AND bm.selected_option_key IN (10)
OR bm.`option_type` = 'bzips'  
AND bm.selected_option_key IN (37027)
GROUP BY b.b_id 

答案 1 :(得分:0)

也许你是在追求这样的事情......

SELECT DISTINCT b.b_id 
  FROM buy b 
  JOIN buy_multiples bm 
    ON bm.b_id = b.b_id 
 WHERE b.buy_status IN (2)  
   AND (
        (bm.option_type = 'area_id' AND bm.selected_option_key IN (10)) 
     OR (bm.option_type = 'bzips' AND bm.selected_option_key IN (37027))
       );