1

我有这个 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

我想选择 deals.partner_id = 62039 IF Deals.partner_count 为 1 的位置。

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

如何才能做到这一点?

4

3 回答 3

2

尝试

where
case when deals.partner_count = 1 
   then deals.partner_id = 62039
   else refnumbers.claim_track_id = 62039
end
于 2013-01-17T13:08:15.530 回答
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
于 2013-01-17T13:06:30.343 回答
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
于 2013-01-17T16:02:56.290 回答