如果WHERE条件没有返回结果,请尝试另一个?

时间:2015-02-05 21:43:16

标签: mysql sql

我不想要这个:

SELECT * FROM table
WHERE condition1
OR condition2
OR condition3    

相反,我想要这个:

SELECT * FROM table
WHERE condition1
    (if no result)
        try condition2
            (if no result)
                try condition3

我怎样才能在MySQL中写这个?因此,如果找到结果,则不要尝试下面的条件。

6 个答案:

答案 0 :(得分:1)

您可以像这样使用UNION

SELECT *
FROM table
WHERE condition1

UNION

SELECT *
FROM table
WHERE condition2 AND NOT EXISTS (SELECT 1 FROM table WHERE condition1)

UNION 

SELECT *
FROM table
WHERE condition3 AND NOT EXISTS (SELECT 1 FROM table WHERE condition1) AND
                     NOT EXISTS (SELECT 1 FROM table WHERE condition2)

如果第一个SELECT返回任何行,则第二个和第三个将不返回任何行。否则,如果第二个SELECT返回任何行,则第三个SELECT将不返回任何行。否则,请从第三个SELECT获取结果。

答案 1 :(得分:0)

如果您的目标是了解满足哪些条件,则可以使用UNION查询,如下所示:

SELECT *, 1 as `condition` FROM table WHERE <condition1>
UNION
SELECT *, 2 as `condition` FROM table where <condition2>
UNION
...more conditions

答案 2 :(得分:0)

SQL Fiddle

MySQL 5.5.32架构设置

CREATE TABLE Table1
    (`id` int, `value` varchar(1))
;

INSERT INTO Table1
    (`id`, `value`)
VALUES
    (1, 'a'),
    (2, 'b'),
    (3, 'c'),
    (4, 'd'),
    (5, 'f'),
    (6, 'h'),
    (7, 'i')
;

查询1

SELECT * FROM Table1
WHERE value = 
(case when exists (select 1 from table1 where value='e') then 'e'
     when exists (select 1 from table1 where value='a') then 'a'
     else 'i' end)

<强> Results

| ID | VALUE |
|----|-------|
|  1 |     a |

答案 3 :(得分:0)

您也可以尝试使用WHERE EXISTS语句,如下所示:

SELECT * FROM table
WHERE EXISTS
{Condition 1}
OR EXISTS
{Condition 2}
...more conditions

答案 4 :(得分:0)

你可以避免像这样的联盟:

WHERE condition1 
OR (condition2 AND NOT EXISTS (SELECT 1 FROM table WHERE condition1))
OR (condition3 AND NOT EXISTS (SELECT 1 FROM table WHERE condition1)
       AND NOT EXISTS (SELECT 1 FROM table WHERE condition2)
   )

答案 5 :(得分:-1)

SELECT * FROM table
WHERE val = if(condition1, 'result1', if(condition2, 'result2', if(condition3, 'result3','result')))