2013-01-17 63 views
1

我有這樣的SQL:MySQL查詢具體取決於列的值來定義WHERE語句

SELECT 
    `refnumbers`.`order_id`, 
    `refnumbers`.`deal_id`, 
    `refnumbers`.`claim_track_id`, 
    `deals`.`partner_count` 
FROM `refnumbers` 
    JOIN `deals` 
    ON (`refnumbers`.`deal_id` = `deals`.`ID`) 
    JOIN `users` 
    ON (`users`.`id` = `deals`.`partner_id`) 
WHERE `refnumbers`.`is_claimed` = '1' 
    AND `deals`.`partner_id` = '62039' 
    AND `refnumbers`.`claimed_at` BETWEEN '2013-01-17 00:00:00' 
    AND '2013-01-17 23:59:59' 
ORDER BY `refnumbers`.`claimed_at` DESC 

我想選擇其中deals.partner_id = 62039 IF deals.partner_count爲1

如果未啓用PARTNER_COUNT 1那麼它應該選擇refnumbers.claim_track_id = 62039

這怎麼辦?

+0

可以使用條件的MySQL關鍵字CASE WHEN。 .. THEN ... END – bodi0

回答

1

你需要有一個條件,其中使用了括號括起來OR

SELECT `refnumbers`.`order_id`, 
     `refnumbers`.`deal_id`, 
     `refnumbers`.`claim_track_id`, 
     `deals`.`partner_count` 
FROM `refnumbers` 
     INNER JOIN `deals` 
      ON (`refnumbers`.`deal_id` = `deals`.`ID`) 
     INNER JOIN `users` 
      ON (`users`.`id` = `deals`.`partner_id`) 
WHERE `refnumbers`.`is_claimed` = '1' AND 
     `refnumbers`.`claimed_at` BETWEEN '2013-01-17 00:00:00' AND '2013-01-17 23:59:59' 
     AND 
     (
      (deals.partner_id = 62039 AND deals.partner_count = 1) 
      OR 
      (refnumbers.claim_track_id = 62039 AND deals.partner_count <> 1) 
     ) 
ORDER BY `refnumbers`.`claimed_at` DESC 
+0

MySQL'CASE WHEN ... THEN ... END'可以以更簡單的方式執行此操作:) –

+1

@TrungHieuLe有很多方法可以解決問題,有人已經發布了使用「CASE」的方法。 –

2

嘗試

where 
case when deals.partner_count = 1 
    then deals.partner_id = 62039 
    else refnumbers.claim_track_id = 62039 
end 
0

試試這個:

SELECT r.order_id, r.deal_id,r.claim_track_id, d.partner_count 
FROM refnumbers r 
INNER JOIN deals d ON r.deal_id = d.ID 
INNER JOIN users u ON d.partner_id = u.id 
WHERE IF(d.partner_count = 1, d.partner_id = '62039', r.claim_track_id = 62039) AND 
     r.is_claimed = '1' AND r.claimed_at BETWEEN '2013-01-17 00:00:00' AND '2013-01-17 23:59:59' 
ORDER BY r.claimed_at DESC