gpt4 book ai didi

mysql - 使用 count inside count 时将结果限制为 1 的 SQL 查询

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

我正在尝试选择特定项目的点赞数。我想出的想法是

CAST(count(uploads.ID in (SELECT uploadID from votes)) as decimal) as numberoflikes

这可行,但查询只返回一件事。

整个查询

SELECT DISTINCT users.NAME AS username
,users.ID AS userID
,subjects.NAME AS subjectname
,uploads.TIME
,uploads.description
,uploads.NAME
,uploads.ID
,CASE
WHEN uploads.ID IN (
SELECT uploadID
FROM votes
WHERE userID = 2
)
THEN CAST(1 AS DECIMAL)
ELSE CAST(0 AS DECIMAL)
END AS liked
,CASE
WHEN uploads.ID IN (
SELECT uploadID
FROM bookmarks
WHERE userID = 2
)
THEN CAST(1 AS DECIMAL)
ELSE CAST(0 AS DECIMAL)
END AS bookmarked
,CAST(count(uploads.ID IN (
SELECT uploadID
FROM votes
)) AS DECIMAL) AS numberoflikes
FROM uploads
INNER JOIN subjects ON (subjects.ID = uploads.subjectID)
INNER JOIN users ON (users.ID = uploads.userID)
INNER JOIN uploadGrades ON (uploads.ID = uploadGrades.uploadID)
INNER JOIN grades ON (grades.ID = uploadGrades.gradeID)
WHERE uploads.active = 1
AND subjects.ID IN (
SELECT subjectID
FROM userSubjects
INNER JOIN users ON (users.ID = userSubjects.userID)
WHERE userSubjects.userID = 2
)
AND grades.ID IN (
SELECT userGrades.gradeID
FROM uploadGrades
INNER JOIN userGrades ON (uploadGrades.gradeID = userGrades.gradeID)
WHERE userGrades.userID = 2
)
ORDER BY uploads.trueRating DESC;

最佳答案

让我们尝试减少查询的版本,这是获得更好答案的基础

  1. 我减少了对用户的初始查询,并开始上传。同时删除您已经知道如何计算的字段。

.

SELECT DISTINCT users.NAME AS username
,users.ID AS userID
,uploads.NAME
,uploads.ID
,CAST(count(uploads.ID IN (
SELECT uploadID
FROM votes
)) AS DECIMAL) AS numberoflikes
FROM uploads
INNER JOIN users ON (users.ID = uploads.userID)
WHERE uploads.active = 1
ORDER BY uploads.trueRating DESC;
  • 然后使用LEFT JOIN添加投票来替换COUNT中的SELECT,这样如果不匹配,您将得到NULL 正如我在评论中所说的 COUNT 不算 NULL's
  • .

    SELECT DISTINCT users.NAME AS username
    ,users.ID AS userID
    ,uploads.NAME
    ,uploads.ID
    ,CAST(count(votes.uploadID)) AS DECIMAL) AS numberoflikes
    FROM uploads
    INNER JOIN users ON (users.ID = uploads.userID)
    LEFT JOIN votes ON (uploads.ID = votes.uploadID)
    WHERE uploads.active = 1
    ORDER BY uploads.trueRating DESC;

    关于mysql - 使用 count inside count 时将结果限制为 1 的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35086660/

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