所以我目前正在开展一个项目,我需要根据选择输入字段中的星级来过滤活跃用户。
以下是我的用户表
| id | username | firstname | lastname | description | active |
---------------------------------------------------------------
| 2 | kay | Albert | Kojo | Tall | 1 |
| 3 | kay123 | Mary | Thompson | Tall | 1 |
| 4 | kay124 | Francis | Addai | | 1 |
以下是我的user_reviews表
| id | user_id| rating |
------------------------
| 1 | 2 | 5 |
| 2 | 3 | 3 |
以下是我当前的查询:
$ratings = mysqli_real_escape_string($db, $_POST['rating']);
SELECT
*,
users.id,
FORMAT(AVG( user_reviews.rating ), 1) AS rating_value,
count( user_reviews.user_id ) AS review_count
FROM
users
LEFT JOIN user_reviews ON users.id = user_reviews.user_id
WHERE
users.username LIKE '%%'
AND users.active = 1 AND (users.description != "" OR users.description IS
NOT NULL)
GROUP BY
users.id
HAVING
$ratings <= rating_value
ORDER BY
review_count DESC
以上查询仅返回在user_reviews表中找到的用户。如果有人可以帮助我检索user_reviews表中的用户和不是用户的用户,我将非常高兴。
答案 0 :(得分:0)
您可以尝试此查询:
SELECT
users.*,
(SELECT FORMAT(AVG(rating),1) FROM user_reviews where users.id = user_reviews.user_id) AS rating_value,
(SELECT count(user_id) FROM user_reviews where users.id = user_reviews.user_id) AS review_count
FROM
users
WHERE
users.username LIKE '%%'
AND users.active = 1 AND (users.description != "" OR users.description IS
NOT NULL)
HAVING
$rating <= rating_value
ORDER BY
review_count DESC
它将返回如下输出:
(没有HAVING $rating <= rating_value
)
| id | username |firstname | lastname | description | active | rating_value | review_count |
----------------------------------------------------------------------------------
| 2 | kay | Albert | Kojo | Tall | 1 | 5.0 | 1 |
| 3 | kay123 | Mary | Thompson | Tall | 1 | 3.0 | 1 |
| 4 | kay134 | Francis | Addai | | 1 | NULL | 0 |
(使用HAVING $rating <= rating_value
,其中$rating == 4
)
| id | username |firstname | lastname | description | active | rating_value | review_count |
----------------------------------------------------------------------------------
| 2 | kay | Albert | Kojo | Tall | 1 | 5.0 | 1 |
注意:
我们不需要使用GROUP_BY
因为GROUP_BY
会使您的结果只显示相关的结果。
答案 1 :(得分:0)
更改
GROUP BY
users.id
HAVING
$ratings <= rating_value
要
GROUP BY
users.id
HAVING
(rating >= $ratings or rating IS NULL )
这应该可以解决您丢失的记录。