简体   繁体   English

MySQL“操作顺序”问题

[英]Mysql “order of operations” Question

Here's my situation: I want to SELECT all entries from a database WHERE id = $id. 这是我的情况:我想从WHERE id = $ id的数据库中选择所有条目。 But I want the results to be listed in a certain priority. 但我希望将结果优先列出。 If, criteria = $criteria, then I want those results displayed first. 如果criteria = $ criteria,那么我要首先显示那些结果。 Otherwise, I just want to keep displaying the rest of the rows. 否则,我只想继续显示其余行。

My question is this: will this solve my problem? 我的问题是:这能解决我的问题吗?

SELECT field1 WHERE (criteria=$criteria AND id = $id) OR id=$id  LIMIT 5 

Will the query look at the () first? 查询将首先查看()吗? If not, is there another way to do this without splitting this into two separate queries? 如果不是,是否有另一种方法可以将其分为两个独立的查询呢?

Thanks, 谢谢,
Michael 迈克尔

SELECT  field1
FROM    mytable
WHERE   id = $id
ORDER BY
        criteria = $criteria DESC, id
LIMIT 5

, or this: , 或这个:

SELECT  *
FROM    (
        SELECT  field1
        FROM    mytable
        WHERE   id = $id
                AND criteria = $criteria
        ORDER BY
                id
        LIMIT 5
        ) q
UNION
FROM    (
        SELECT  field1
        FROM    mytable
        WHERE   id = $id
        ORDER BY
                id
        LIMIT 5
        ) q2
ORDER BY
        criteria = $criteria DESC, id
LIMIT 5

The latter is more efficient if you have an index on (id, criteria) (in this order). 如果在(id, criteria) (按此顺序)上具有索引,则后者会更有效。

SELECT field1
  FROM mytable
 WHERE id = $id
 ORDER BY CASE WHEN criteria = $criteria THEN 0 ELSE 1 END CASE
 LIMIT 5;

This will list rows matching the criteria before those not because zero comes before one. 这将列出符合条件的行,而不是不符合条件的行,因为零先于一。

If this won't work directly - as written - then put the info into a sub-query: 如果按照书面说明,这不能直接起作用,则将信息放入子查询中:

SELECT field1
  FROM (SELECT field1,
               CASE WHEN criteria = $criteria THEN 0 ELSE 1 END CASE AS ordering
          FROM mytable
         WHERE id = $id
       ) AS subqry
 ORDER BY ordering
 LIMIT 5;

Often, there will be other secondary criteria to determine the order of rows within the 0 vs 1 ordering. 通常,还会有其他辅助条件来确定0对1排序中的行顺序。

与最初的问题无关,只是为了澄清一下:运算符AND具有比OR更高的优先级,因此为什么a或b与c或d等于a或(b与c)或d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM