MySQL Query根据列值定义where语句

时间:2013-01-17 13:02:53

标签: mysql sql select if-statement

我有这个SQL:

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

我想选择deal.partner_id = 62039 IF deal.partner_count是1。

如果partner_count不是1那么它应该选择refnumbers.claim_track_id = 62039

的位置

如何做到这一点?

3 个答案:

答案 0 :(得分:2)

尝试

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

答案 1 :(得分: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

答案 2 :(得分: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