卡在 SQL 查询上来计算行数

发布于 2024-11-16 22:16:03 字数 475 浏览 6 评论 0原文

SELECT 
  COUNT(*) AS TotalUserVotes
FROM tblArticleVotes AS v 
INNER JOIN tblArticles AS a 
  ON v.ArticleID = a.ID 
     AND a.AuthorID = 13405

它始终返回 0。我有一个表 tblArticles,其中包含 AuthorIDID(文章的主键)。

然后我有一个文章投票表,其中有一个 articleID 列。

给定用户13405,我需要找出他们在所有文章中拥有多少票!

需要确认的是,当前 tblArticleVotes 中有一条文章 ID 为 5 的记录。文章 ID 5 的作者 ID 为 13405。

SELECT 
  COUNT(*) AS TotalUserVotes
FROM tblArticleVotes AS v 
INNER JOIN tblArticles AS a 
  ON v.ArticleID = a.ID 
     AND a.AuthorID = 13405

This always returns 0. I have a table tblArticles which has an AuthorID and ID (primary key for article).

I then have an article votes table, with an articleID column.

Given user 13405 I need to find out how many votes they have across all of their articles!

Just to confirm, there is currently one record in tblArticleVotes which has the articleID of 5. Article ID 5 has the author ID of 13405.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

孤独患者 2024-11-23 22:16:03

嗯... JOIN 中的 AuthorID 看起来很奇怪...也许这样效果更好?

SELECT COUNT(*) AS TotalUserVotes
  FROM tblArticleVotes AS v INNER JOIN
  tblArticles AS a ON v.ArticleID = a.ID
  WHERE a.AuthorID = 13405

Hmmm... the AuthorID in the JOIN looks odd... maybe this works better?

SELECT COUNT(*) AS TotalUserVotes
  FROM tblArticleVotes AS v INNER JOIN
  tblArticles AS a ON v.ArticleID = a.ID
  WHERE a.AuthorID = 13405
依 靠 2024-11-23 22:16:03

尝试将“AND”更改为“WHERE”:

SELECT COUNT(*) AS TotalUserVotes
FROM tblArticleVotes AS v INNER JOIN
tblArticles AS a ON v.ArticleID = a.ID WHERE a.AuthorID = 13405

HTH

Try changing the "AND" to "WHERE":

SELECT COUNT(*) AS TotalUserVotes
FROM tblArticleVotes AS v INNER JOIN
tblArticles AS a ON v.ArticleID = a.ID WHERE a.AuthorID = 13405

HTH

潇烟暮雨 2024-11-23 22:16:03

你的查询没有任何问题。要解决此问题,请分解查询。

DECLARE @ArticleID int
SELECT @ArticleID = a.ID FROM tblArticles a WHERE a.AuthorID=13405

PRINT @ArticleID
SELECT * FROM tblArticleVotes where ArticleID=@ArticleID

There is nothing wrong with your query. To trouble shoot this break the query up.

DECLARE @ArticleID int
SELECT @ArticleID = a.ID FROM tblArticles a WHERE a.AuthorID=13405

PRINT @ArticleID
SELECT * FROM tblArticleVotes where ArticleID=@ArticleID
回忆躺在深渊里 2024-11-23 22:16:03

试试这个:

SELECT a.AuthorID, COUNT(v.id) as votes
FROM tblArticles AS a 
LEFT JOIN tblArticleVotes AS v ON a.ID = v.ArticleID
GROUP BY a.ID
WHERE a.AuthorID = :author_id

try this instead:

SELECT a.AuthorID, COUNT(v.id) as votes
FROM tblArticles AS a 
LEFT JOIN tblArticleVotes AS v ON a.ID = v.ArticleID
GROUP BY a.ID
WHERE a.AuthorID = :author_id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文