gpt4 book ai didi

mysql - PHP MySQL 从 MySQL 返回不同的结果

转载 作者:行者123 更新时间:2023-11-29 02:58:16 25 4
gpt4 key购买 nike

当我在 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
)

最佳答案

初始化@businessType变量

试试这个:

SELECT RowNum,store_ID,businessType,createDate,expirationDate 
FROM (SELECT IF(@businessType = @businessType:=businessType, @ctr := @ctr + 1, @ctr := 1) as RowNum,
businessType, store_ID, createDate, expirationDate
FROM stores, (SELECT @ctr := 1, @businessType := 0) 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 - PHP MySQL 从 MySQL 返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27665960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com