0

有没有办法可以结合这两个 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;
4

5 回答 5

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;
于 2012-12-03T15:17:40.297 回答
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;

括号是你的朋友年轻的帕万。当然,我假设您想要满足任一条件的记录。

于 2012-12-03T15:20:28.950 回答
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;
于 2012-12-03T15:18:29.357 回答
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;
于 2012-12-03T15:19:26.270 回答
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;

可能是这样的,但如果语法正确则不确定

于 2012-12-03T15:20:26.690 回答