简体   繁体   English

运行相同查询时的MySQLi结果集更改

[英]MySQLi result set chaning when running the same query

Having a fairly simple query 有一个相当简单的查询

SELECT
    af_ad.*, af_ad_to_interest.interest_id
FROM af_ad
LEFT JOIN af_adlike ON af_adlike.ad_id = af_ad.ad_id
LEFT JOIN af_ad_to_interest ON af_ad_to_interest.ad_id = af_ad.ad_id
LEFT JOIN af_ad_stats ON af_ad_stats.ad_id = af_ad.ad_id
WHERE
    (af_adlike.user_id = 1 AND af_adlike.adlike_action = 1)
    AND af_ad.ad_deleted = 0 AND af_ad.ad_accepted = 1
GROUP BY af_ad.ad_id, af_ad_to_interest.interest_id
ORDER BY af_ad.ad_date_created DESC, af_ad.ad_id

results in a set that remains the same for most of the runs (query executions) but still somehow the result set happens to have changed row order in a few occasions (manual test, result set is relatively small ~2000 rows, happens ~5th time). 结果集在大多数运行(查询执行)中都保持不变,但是结果集在某些情况下碰巧改变了 行顺序 (手动测试,结果集相对较小,约2000行,第5次发生) )。

The respective PHP code is 各自的PHP代码是

$handle = new mysqli($db_host, $db_user, $db_password, $db_name);
$result = $handle->query($query);

Read about possible solutions here about mysqli queries/parameters , could passing/implementing an extra parameter MYSQLI_USE_RESULT or using mysqli_free_result , closing connection, etc., could solve it? 在此处阅读有关mysqli查询/参数的可能解决方案,可以传递/实现一个额外的参数MYSQLI_USE_RESULT或使用mysqli_free_result ,关闭连接等方法是否可以解决?

Edit 1: 编辑1:

Here are the output arrays: 这是输出数组:

Most cases: 在大多数情况下:

[0] => 15
[1] => 19
**[2] => 10**
[3] => 17
[4] => 12
[5] => 9
[6] => 16
[7] => 18
[8] => 9
[9] => 9
[10] => 12
[11] => 10
[12] => 11
[13] => 11
[14] => 18
[15] => 2
[16] => 20

Some cases: 一些案例:

[0] => 15
[1] => 19
[2] => 17
[3] => 12
[4] => 9
[5] => 16
**[6] => 10**
[7] => 18
[8] => 9
[9] => 9
[10] => 12
[11] => 10
[12] => 11
[13] => 11
[14] => 18
[15] => 2
[16] => 20

Edit 2: 编辑2:

Found another possible pitfall. 发现另一个可能的陷阱。 I am running two queries sequentially, like 我依次运行两个查询,例如

$result1 = $handle->query($query1);
$result2 = $handle->query($query2);

Could it be possible it somehow caches/stores the previous results (although the $query1 and $query2 are quite different. 是否有可能以某种方式缓存/存储先前的结果(尽管$query1$query2完全不同。

Avoid having in SELECT columns that are not in GROUP BY: 避免在不在GROUP BY中的SELECT列中使用:

SELECT
    af_ad.ad_id, af_ad_to_interest.interest_id, min(af_ad.ad_date_created) as min_ad_date_created
FROM af_ad
LEFT JOIN af_adlike ON af_adlike.ad_id = af_ad.ad_id
LEFT JOIN af_ad_to_interest ON af_ad_to_interest.ad_id = af_ad.ad_id
LEFT JOIN af_ad_stats ON af_ad_stats.ad_id = af_ad.ad_id
WHERE
    (af_adlike.user_id = 1 AND af_adlike.adlike_action = 1)
    AND af_ad.ad_deleted = 0 AND af_ad.ad_accepted = 1
GROUP BY af_ad.ad_id, af_ad_to_interest.interest_id
ORDER BY min_ad_date_created DESC, af_ad.ad_id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM