将2个查询组合到一个查询中

时间:2013-10-10 07:40:52

标签: mysql sql

我有2个查询

Select * From wp_booking_transaction
Where DATE(launched) >= "2013-10-10" And DATE(launched) <= "2013-11-10" 
And action = 1 status = 1 And type = 2 And student_id = 81569 
Order by launched desc

Select * From wp_booking_transaction 
Where (DATE(launched) >= "2013-10-10" And DATE(launched) <= "2013-11-10" 
And status = 0 And type = 2 And student_id = 81569) And (action = 21 Or action = 20) 
Order by launched desc

需要量:

获取action = 1status = 1的行以及(action = 20 or action = 21)status = 0的行。

谢谢!

3 个答案:

答案 0 :(得分:2)

尝试使用UNION

Select 
    * 
From 
    wp_booking_transaction 
Where 
    DATE(launched) >= "2013-10-10" 
    And DATE(launched) <= "2013-11-10" 
    And action = 1 
    And status = 1 
    And type = 2 
    And student_id = 81569 

UNION ALL

Select 
    * 
From 
    wp_booking_transaction 
Where (
        DATE(launched) >= "2013-10-10" 
        And DATE(launched) <= "2013-11-10" 
        And status = 0 
        And type = 2 
        And student_id = 81569
    ) 
    And (
        action = 21 
        Or action = 20
    ) 
Order by launched desc

BTW 这个:

And (
        action = 21 
        Or action = 20
    ) 

可以写成

And action IN (21,20)

答案 1 :(得分:1)

SELECT   *
FROM     wp_booking_transaction
WHERE    /* Conditions that appeared in both original queries */
         DATE(launched) >= "2013-10-10" 
AND      DATE(launched) <= "2013-11-10"
AND      type = 2 
AND      student_id = 81569
AND      /* Conditions that are different between the two queries */
         ((action = 1 AND status = 1) OR (action IN(20, 21) AND status = 0))
ORDER BY launched DESC

答案 2 :(得分:0)

您可以使用 union all |两个查询之间的

Select * From wp_booking_transaction
Where DATE(launched) >= "2013-10-10" And DATE(launched) <= "2013-11-10" 
And action = 1 status = 1 And type = 2 And student_id = 81569 
union all
Select * From wp_booking_transaction 
Where (DATE(launched) >= "2013-10-10" And DATE(launched) <= "2013-11-10" 
And status = 0 And type = 2 And student_id = 81569) And (action = 21 Or action = 20) 
Order by launched desc