选择条件1遵循条件2的记录

时间:2016-06-16 11:43:20

标签: mysql

在我的项目中,我有类似的查询。

$mainquery="SELECT * 
            FROM project 
            WHERE ProjectType='Current Projects' and Status='In Progress' 
            order by projectid";

$mainquery="SELECT * 
            FROM project 
            WHERE ProjectType='Current Projects' and Status='Not Started' 
            order by projectid";

现在我希望将两者结合起来并希望所有记录Status ='In Progress'然后Status ='Not Started'。我试过这个。

$mainquery="SELECT * 
            FROM project 
            WHERE ProjectType='Current Projects' and (Status='In Progress' or Status='Not Started') 
            order by projectid";

但是它给出了Status ='In Progress'和Status ='Not Started'的组合结果。我想首先记录Status ='In Progress',然后记录Status ='Not Started'。

5 个答案:

答案 0 :(得分:1)

这些方面的某些内容可能很有用

SELECT * 
      FROM project 
      WHERE ProjectType='Current Projects' and (Status='In Progress' or  
      Status='Not Started') 
      order by case when Status like 'In Progress' then 0 else 1 end, Status

参考:https://dba.stackexchange.com/questions/96446/mysql-order-by-first-condition-in-where-clause

答案 1 :(得分:0)

$mainquery="SELECT * FROM project WHERE ProjectType='Current Projects' and 
           (Status='In Progress' or Status='Not Started') 
           order by  Status <> 'Not Started',projectid";

答案 2 :(得分:0)

.form-inline text, .form-inline label {
    margin: 0px 3px 0px 3px !important;
}

答案 3 :(得分:0)

如果您的意思是说您正在获得所有结果,状态=&#34;正在进行中&#34;那些状态=&#34;未开始&#34;,交错,仅由&#34; projectid&#34;排序。

您希望看到&#34;进展中的结果&#34;首先然后&#34;未开始&#34; (均根据项目进行排序),然后您必须执行以下操作之一:


$ mainquery =
&#34; SELECT *
            来自项目
            在哪里ProjectType =&#39;当前项目&#39;和(状态=&#39;进行中&#39;或状态=&#39;未开始&#39;)             按状态排序,projectid&#34 ;;

这将首先根据状态(按字母顺序 升序,即&#34;进行中&#34;之前& #34;未开始&#34;)然后在具有相同状态的结果中,它将根据他们的&#34; projectid&#34;的数值(升序)。

答案 4 :(得分:-1)

SELECT * FROM project WHERE ProjectType='Current Projects' and Status='In Progress' order by projectid
UNION ALL
SELECT * FROM project WHERE ProjectType='Current Projects' and Status='Not Started' order by projectid

上面会给你第一个条件的记录然后 提供第二个条件的记录,两个查询的列数保持不变。

 SELECT * FROM project WHERE ProjectType='Current Projects' and (Status='In Progress' OR Status='Not Started') order by projectid

以上查询也适用于您的情况。