作为IF语句的结果,将条件应用于MySQL

时间:2016-01-30 11:25:54

标签: mysql if-statement

我有一个问题:

SELECT campaign_id, campaign_balance, campaign_email
FROM campaigns
WHERE campaign_unique = 0
LIMIT 1

但是我只想在以下内容返回一个时将WHERE campaign_unique = 0条件应用于上述查询:

SELECT COUNT(earning_id) FROM earnings WHERE earning_ip = '77.166.56.152' LIMIT 1

我是否可以通过某种方式应用IF语句来决定是否应用WHERE条件?

1 个答案:

答案 0 :(得分:1)

您可以在WHERE中应用if():

SELECT 
    campaign_id, campaign_balance, campaign_email
FROM campaigns
WHERE
    campaign_unique = if (some_condition, campaign_unique, 0)
LIMIT 1

这意味着:如果some_condition被评估为TRUE,则WHERE条件应为campaign_unique = campaign_unique(或者根本不应用条件),如果评估为FALSE,则WHERE条件应为campaign_unique = 0。 所以,对于你的情况,它可能是这样的:

SELECT
    campaign_id, campaign_balance, campaign_email
FROM campaigns
WHERE
    campaign_unique = if (
        (SELECT COUNT(earning_id) FROM earnings WHERE earning_ip = '77.166.56.152' LIMIT 1) = 1, 
        campaign_unique, 
        0
    )
LIMIT 1

或者将子查询的结果存储在变量中以简化查询:

SET @earningsCount = (SELECT COUNT(earning_id) FROM earnings WHERE earning_ip = '77.166.56.152' LIMIT 1);

SELECT
    campaign_id, campaign_balance, campaign_email
FROM campaigns
WHERE
    campaign_unique = if (
        @earningsCount = 1,
        campaign_unique,
        0
    )
LIMIT 1