结合MySQL查询?

时间:2012-12-03 15:16:25

标签: php mysql

有没有办法将这两个MySQL查询结合起来?它目前正在进行排序和分页等非常困难。

SELECT *
FROM (`lb_sales`)
WHERE `recurring` =  '0'
AND `created` >= '2012-10-01 00:00:00'
AND `created` <= '2012-10-30 23:59:59'
AND `status` =  'pending'
AND `type` =  'sale'
AND `account_id` =  '2'
ORDER BY `id` ASC
LIMIT 5;

SELECT *
FROM (`lb_sales`)
WHERE `recurring` =  '1'
AND `created` <= '2012-10-30 23:59:59'
AND `status` =  'pending'
AND `type` =  'sale'
AND `account_id` =  '2'
ORDER BY `id` ASC
LIMIT 5;

5 个答案:

答案 0 :(得分:1)

尝试UNION ALL,只需确保列对齐即可。另外,请勿使用SELECT *。始终指定列列表。

SELECT col1, col2, ...
FROM (`lb_sales`)
WHERE `recurring` =  '0'
AND `created` >= '2012-10-01 00:00:00'
AND `created` <= '2012-10-30 23:59:59'
AND `status` =  'pending'
AND `type` =  'sale'
AND `account_id` =  '2'
ORDER BY `id` ASC
LIMIT 5
UNION ALL
SELECT col1, col2, ...
FROM (`lb_sales`)
WHERE `recurring` =  '1'
AND `created` <= '2012-10-30 23:59:59'
AND `status` =  'pending'
AND `type` =  'sale'
AND `account_id` =  '2'
ORDER BY `id` ASC
LIMIT 5;

答案 1 :(得分:1)

SELECT *
FROM (`lb_sales`)
WHERE
(
`recurring` =  '0'
AND `created` >= '2012-10-01 00:00:00'
AND `created` <= '2012-10-30 23:59:59'
)
OR
( 
`recurring` =  '1'
AND `created` <= '2012-10-30 23:59:59'
)
AND `status` =  'pending'
AND `type` =  'sale'
AND `account_id` =  '2'
ORDER BY `id` ASC
LIMIT 5;

括号是你的朋友年轻的padwan。当然,我假设你想要符合任何一个标准的记录。

答案 2 :(得分:0)

SELECT *
FROM (`lb_sales`)
WHERE ((`recurring` =  '0'
AND `created` >= '2012-10-01 00:00:00'
AND `created` <= '2012-10-30 23:59:59')
OR (`recurring` =  '1'
AND `created` <= '2012-10-30 23:59:59'))
AND `status` =  'pending'
AND `type` =  'sale'
AND `account_id` =  '2'
ORDER BY `id` ASC
LIMIT 10;

答案 3 :(得分:0)

尝试:

SELECT *  FROM (`lb_sales`)
WHERE (`recurring` =  '0' AND `created` >= '2012-10-01 00:00:00'
 AND `created` <= '2012-10-30 23:59:59' ) 
OR (`recurring` =  '1' AND `created` <= '2012-10-30 23:59:59')    
AND `status` =  'pending'
AND `type` =  'sale'
AND `account_id` =  '2'
ORDER BY `id` ASC
LIMIT 5;

答案 4 :(得分:0)

SELECT *
FROM (`lb_sales`)
WHERE ( `recurring` =  '0' 
AND `created` >= '2012-10-01 00:00:00'
AND `created` <= '2012-10-30 23:59:59'
AND `status` =  'pending'
AND `type` =  'sale'
AND `account_id` =  '2' ) 
OR  (`recurring` =  '1'
AND `created` <= '2012-10-30 23:59:59'
AND `status` =  'pending'
AND `type` =  'sale'
AND `account_id` =  '2' )
ORDER BY `id` ASC
LIMIT 5;

可能是这样的,但不确定语法是否正确