gpt4 book ai didi

php - MySQL Join 返回超过预期

转载 作者:行者123 更新时间:2023-11-29 02:48:49 24 4
gpt4 key购买 nike

这个问题让我睡了 2 天。

我有两张 table

views 

id | postid | date | count
=================================
13 | 8 | 2016-07-16 | 38
16 | 8 | 2016-07-17 | 35
15 | 9 | 2016-07-16 | 7
17 | 9 | 2016-07-17 | 32
14 | 12 | 2016-07-16 | 17
18 | 12 | 2016-07-17 | 13


visitors

id | postid | date | ip
=================================
13 | 8 | 2016-07-16 | 127.0.0.1
17 | 8 | 2016-07-17 | 127.0.0.1
18 | 8 | 2016-07-17 | 127.0.0.1
16 | 9 | 2016-07-16 | 127.0.0.1
19 | 9 | 2016-07-17 | 127.0.0.1
14 | 12 | 2016-07-16 | 127.0.0.1
15 | 12 | 2016-07-16 | 127.0.0.1
20 | 12 | 2016-07-17 | 127.0.0.1
21 | 12 | 2016-07-17 | 127.0.0.1

和下面的查询

$query = $wpdb->get_results("
SELECT
SUM(a.count) AS countviews,
COUNT(b.ip) AS countvisitors,
a.postid
FROM views a
RIGHT JOIN visitors b
ON a.postid=b.postid
AND a.date=b.date
WHERE
a.date
BETWEEN
DATE_SUB('2016-07-17', INTERVAL 3 DAY)
AND
'2016-07-17'
GROUP BY
a.postid
ORDER BY
countviews DESC
");

当我 print_r 输出时,我会看到以下结果

Array
(
[0] => stdClass Object
(
[countviews] => 108
[countvisitors] => 3
[postid] => 8
)

[1] => stdClass Object
(
[countviews] => 60
[countvisitors] => 4
[postid] => 12
)

[2] => stdClass Object
(
[countviews] => 39
[countvisitors] => 2
[postid] => 9
)

)

只有 [countviews] 结果高于预期。我要数一下,看看来自 postid 8 的 countviews 一定不是“108”,而是“73”。奇怪的是 postid 8 的最后计数是“35”。 “108”减去“35”=“73”。所以 View 表是双倍的?

RIGHT JOIN、LEFT JOIN 和 INNER JOIN 给出的结果都是一样的。

最佳答案

如果要计数,则不能在此处进行连接。您建立的关系是创建 View 表的倍数,以防同一 postid 在您的搜索参数中有多个日期。

您可以通过使用子查询来避免这种情况:

SELECT
SUM(a.count) AS countviews,
(SELECT COUNT(b.ip) FROM visitors i WHERE b.date BETWEEN DATE_SUB("2016-07-17", INTERVAL 3 DAY) AND "2016-07-17" AND i.postid = a.postid) AS countvisitors,
a.postid
FROM views a
WHERE
a.date
BETWEEN
DATE_SUB('2016-07-17', INTERVAL 3 DAY)
AND
'2016-07-17'
GROUP BY
a.postid
ORDER BY
countviews DESC

希望我做对了。让我知道这是否有帮助:)

关于php - MySQL Join 返回超过预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38433451/

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