MySQL:这是真的,如果没有,那么这个

时间:2013-01-28 06:02:02

标签: mysql conditional-statements where where-clause

我的查询:

SELECT *
FROM ranks
WHERE
    (price = 25.00 AND accumulate = 0)
    OR
    (price <= (SELECT SUM(amount) FROM donations WHERE username = 'username' AND amount IN (SELECT price FROM ranks WHERE accumulate = 1)))
ORDER BY price
DESC LIMIT 1

基本上我想在找到匹配项时返回第一个where子句,否则返回第二个子句。

2 个答案:

答案 0 :(得分:1)

此查询将起作用

SELECT *
FROM ranks
WHERE price = 25.00 AND accumulate = 0

UNION ALL

SELECT *
FROM ranks
WHERE NOT EXISTS(SELECT *
                  FROM ranks
                  WHERE price = 25.00 AND accumulate = 0)
      AND (price <= (SELECT SUM(amount) FROM donations WHERE username = 'username' AND        amount IN (SELECT price FROM ranks WHERE accumulate = 1)))
ORDER BY price
DESC LIMIT 1

答案 1 :(得分:0)

使用IF

尝试此查询
SELECT *
FROM ranks
WHERE if(price = 25.00,accumulate = 0, price <= (SELECT
                           SUM(amount)
                         FROM donations
                         WHERE username = 'username'
                             AND amount IN(SELECT
                                     price
                                   FROM ranks
                                   WHERE accumulate = 1)))
ORDER BY price DESC
LIMIT 1