且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL计数复杂查询结果?

更新时间:2023-01-29 08:32:45

您的问题是, 't返回你认为它返回(它总是有助于运行你查询单独,看看结果集是否是你期望的)。

Your problem is, your query isn't returning what you think it returns (it always helps to run you query standalone, to see if the result set is what you expect).

右键,让我们打破这个


它会计算用户没有赞成或不喜欢的所有帖子。喜欢和不喜欢被存储在出租车的表。 taxi.taxiID与post.ID匹配。因此,如果找到任何值不为null的userID,请忽略该post.ID。

It is counting all posts that the user has not liked or disliked. likes and dislikes are stored in the taxi table. taxi.taxiID matches post.ID. Hence if the userID with any value that isn't null is found, ignore that post.ID. I am counting those post.ID which are not ignored

您正在计算所有帖子不要

You're trying count all posts that don't have a matching record in the taxi table, for that userID. What you want here is to JOIN the tables and get those rows in post that would normally be excluded by the join. This is achieved by an left outer join

编辑)实现的。

SELECT p.ID, t.taxiID
FROM post p LEFT OUTER JOIN taxi t ON p.ID = t.taxiID AND t.userID = '.$user.'
HAVING t.taxiID IS NULL

HAVING 子句表示:只有结果集中没有相应的t.taxiID的行。

That HAVING clause is saying: only those rows in the resultset that didn't have a corresponding t.taxiID.

如果运行此查询并获取预期的行没有该用户的喜欢或不喜欢)那么您可以添加一个外部查询来计算返回的行数:

If you run this query and get the expected set of rows (posts that do not have likes or dislikes by that user) THEN you can add an outer query to count the number of returned rows:

SELECT COUNT(*) as count FROM (
    SELECT p.ID, t.taxiID
    FROM post p LEFT OUTER JOIN taxi t ON p.ID = t.taxiID AND t.userID = '.$user.'
    HAVING t.taxiID IS NULL
) a

单个标量命名计数。在这种情况下,您可以说:

This should return a single scalar named count. In this case you'll be able to say:

if ($count[0]->count > 10) { blah blah blah }

第二次编辑您的那些帖子在出租车表中有值= 1,或没有值,这导致4为您的示例返回:

(2nd edit) This inner query will get you those posts that have either value = 1 in the taxi table, or no value at all, which results in 4 being returned for your example:

SELECT p.ID, t.taxiID, t.value
FROM post p LEFT OUTER JOIN taxi t ON p.ID = t.taxiID AND t.userID = '.$user.'
HAVING t.taxiID IS NULL OR t.value = 1