2

我正在使用 MySQL v5.5.27。我通常会这样写这个 SELECT 语句:

SELECT DISTINCT * 
FROM table 
WHERE something = 'this' 
    OR something = 'that' 
    OR something = 'other' 
    AND thingamajig = 'one' 
    OR thingamajig = 'two'

但是这个 SELECT 语句会提供完全相同的结果吗?

SELECT DISTINCT * 
FROM table 
WHERE something = ('this' OR 'that' OR 'other') 
    AND thingamajig = ('one' OR 'two')

我试过运行它,它似乎正在工作。只是想确保第二种做事方式不会以某种我想不到的方式返回错误数据。

感谢您的任何见解,帮助!

4

4 回答 4

6

我建议使用括号来清楚地对搜索条件的顺序进行分组。

你的第二个SELECT陈述比你的第一个更清楚。

SELECT DISTINCT * 
FROM table 
WHERE something = ('this' OR 'that' OR 'other') 
AND thingamajig = ('one' OR 'two')

请记住,IN当您有多个值时,您也可以使用运算符:

SELECT DISTINCT * 
FROM table 
WHERE something IN ('this', 'that', 'other') 
AND thingamajig IN ('one', 'two')

此外,使用IN运算符的执行速度比使用OR.

于 2012-09-26T15:10:21.607 回答
4

AND ORSQL中优先。这意味着您的第一个查询等同于:

SELECT DISTINCT * 
FROM table 
WHERE something = 'this' 
    OR something = 'that' 
    OR (something = 'other' AND thingamajig = 'one') 
    OR thingamajig = 'two' 

这显然与您的第二个查询结果不同,并且可能不是您的预期行为。

在这种情况下,您可以使用IN,这恰好可以解决您的问题,但总的来说,最好了解运算符优先级,以便您了解各种 AND 和 OR 组合的结果。

因此,为了清楚起见,您可以将第一个查询重写为:

SELECT DISTINCT *     
FROM table     
WHERE (something = 'this'         
        OR something = 'that'         
        OR something = 'other')         
    AND (thingamajig = 'one'         
        OR thingamajig = 'two')

然后将其转换为 useIN语句对输出没有影响,而且对性能也没有影响,所以更多的是编码风格和优雅的问题。

于 2012-09-26T15:11:41.143 回答
2

Use IN instead of =.

SELECT DISTINCT * 
FROM table 
WHERE something IN ('this', 'that', 'other') AND 
      thingamajig IN ('one', 'two')

IN is similar to OR so performance is the same. Your second query produces syntax error. Because only comma is allowed in IN clause.

SELECT DISTINCT * 
FROM table 
WHERE something = ('this' OR 'that' OR 'other') 
    AND thingamajig = ('one' OR 'two')
于 2012-09-26T15:09:46.377 回答
0

您也可以像这样使用 UNION:

SELECT 
  DISTINCT * 
FROM 
   table 
WHERE 
    something = ('this', 'that', 'other') 
UNION
SELECT 
  * 
FROM 
   table 
WHERE 
   thingamajig IN ('one', 'two')

使用每个 SELECT 的标志变量可以更“识别”您的查询...

SELECT
  'FOO_CASE_1' as case
FROM
  DUAL
UNION
SELECT
  'FOO_CASE_2' as case
FROM
  DUAL
ORDER BY
  1

这种方式让你的调试更容易;)

于 2012-09-26T18:04:04.027 回答