当我在 MySQL 中运行查询时,我得到了预期的结果。该查询使用 MySQL 定义的变量按前 n 个分组。但是,在 PHP 中运行时,似乎“IF(@businessType=businessType...) 没有被正确评估并导致它选择所有结果。查询是:
SELECT RowNum,store_ID,businessType,createDate,expirationDate
FROM (
SELECT IF(@businessType = businessType, @ctr := @ctr + 1, @ctr := 1) as RowNum,
@businessType := businessType as businessType, store_ID, createDate, expirationDate
FROM stores
JOIN (SELECT @ctr := 1) AS a
WHERE businessType IN (1,2,3)
AND ZIP = '11217'
AND state = 'NY'
ORDER BY businessType, createDate DESC) AS b
WHERE RowNum in (1,2,3)
MySQL的结果是:
+--------+----------+--------------+---------------------+----------------+
| RowNum | store_ID | businessType | createDate | expirationDate |
+--------+----------+--------------+---------------------+----------------+
| 1 | 4455977 | 1 | 2014-12-27 04:16:38 | 2014-12-31 |
| 2 | 4455977 | 1 | 2014-12-27 04:16:38 | 2014-12-31 |
| 3 | 1971257 | 1 | 2014-12-27 04:01:35 | 2014-12-31 |
| 1 | 3883533 | 2 | 2014-12-27 04:10:26 | 2015-01-01 |
| 2 | 3718085 | 2 | 2014-12-27 04:10:18 | 2015-01-01 |
| 3 | 3718085 | 2 | 2014-12-27 04:10:17 | 2015-01-01 |
| 1 | 2170979 | 3 | 2014-12-27 04:09:56 | 2015-01-10 |
| 2 | 2034241 | 3 | 2014-12-27 04:09:56 | 2015-01-10 |
| 3 | 2220899 | 3 | 2014-12-27 04:09:56 | 2015-01-10 |
+--------+----------+--------------+---------------------+----------------+
在 PHP 中,它返回 50 个结果,并且 RowNum 字段没有按预期递增。如何更正此查询以使其正确尊重“@”符号?注意:我在 PHP 中使用单引号,所以它不应该评估 '@' 符号。这是输出的一个片段:
Array
(
[RowNum] => 1
[businessType] => 1
[createDate] => 2014-12-27 04:16:38
[expirationDate] => 2014-12-31
)
Array
(
[RowNum] => 1
[businessType] => 1
[createDate] => 2014-12-27 04:16:38
[expirationDate] => 2014-12-31
)
Array
(
[RowNum] => 1
[businessType] => 1
[createDate] => 2014-12-27 04:01:35
[expirationDate] => 2014-12-31
)
Array
(
[RowNum] => 1
[businessType] => 1
[createDate] => 2014-12-27 04:01:35
[expirationDate] => 2014-12-31
)
Array
(
[RowNum] => 1
[businessType] => 1
[createDate] => 2014-12-27 03:45:55
[expirationDate] => 2014-12-29
)
...
Array
(
[RowNum] => 1
[businessType] => 3
[createDate] => 2014-12-27 03:27:28
[expirationDate] => 2014-12-29
)