我用INNER JOIN和子查询编写了SQL查询:
SELECT c.*,
ar.ArticleName,
ar.idArticle,
du.DetailToUsersName,
du.DetailToUsersPhoto,
COUNT(c.idCommentToArticle) AS CNT,
CASE WHEN d.Count IS NULL THEN 0 ELSE d.Count END AS CountLikes
from (select *
from commenttoarticle g
inner join (select distinct(s.idCommentToArticle)
from commenttoarticle s
order by s.CommentToArticlePID limit 3) as gh) as c
LEFT JOIN article ar ON c.CommentToArticleIdArticle = ar.idArticle
LEFT JOIN detailtousers du ON du.idDetailToUsers = c.CommentToArticleIdUser
LEFT JOIN `likes` d ON (d.IdNote = c.idCommentToArticle AND d.LikeType = 6)
WHERE c.CommentToArticleIdArticle = 11
GROUP BY c.idCommentToArticle
ORDER BY c.idCommentToArticle DESC
所以,我得到错误:
重复列名称' idCommentToArticle'
我无法找到重复的位置?
答案 0 :(得分:2)
您可以在别名表中指定查询c
select g.* from commenttoarticle g
而不是
select * from commenttoarticle g
此外,您应该指定Join条件,根据您的意图将行限制为3,除了ON子句,它将像交叉连接一样。
select g.* from commenttoarticle g
inner join (select distinct(s.idCommentToArticle) from commenttoarticle s order by s.CommentToArticlePID limit 3) as gh
on g.idcommenttoarticle = gh.idcommenttoarticle
答案 1 :(得分:0)
正如@RADAR所建议的那样,你的内部查询连接似乎并不完整。我从评论中看到,一旦你将JOIN条件放入,你就会丢失所有数据。我认为这是因为子查询中的任何一部分都没有按照他们应该做的那样做。
这是我对整体解决方案的尝试(注意,没有数据集和表定义我无法显示它的工作原理)。好的,所以你再次通过here提出了问题并提供了SQL-Fiddle,我已经更新了工作版本,但是减去了额外的JOIN表,因为它们没有定义。
SELECT c.*,
ar.ArticleName,
ar.idArticle,
du.DetailToUsersName,
du.DetailToUsersPhoto,
COUNT(c.idCommentToArticle) AS CNT,
CASE WHEN d.Count IS NULL THEN 0 ELSE d.Count END AS CountLikes
FROM commenttoarticle c -- one layer of subquery not required.
INNER JOIN (select s.idCommentToArticle, s.CommentToArticlePID -- added both the id and the parent id
FROM commenttoarticle s
WHERE s.CommentToArticleIdArticle = 11 -- moved to inner query, instead of outer query
ORDER BY s.idCommentToArticle DESC limit 3) as gh
ON c.idcommenttoarticle = gh.idcommenttoarticle -- add join condition
OR c.idcommenttoarticle = gh.CommentToArticlePID -- which matches id and parent id
LEFT JOIN article ar ON c.CommentToArticleIdArticle = ar.idArticle
LEFT JOIN detailtousers du ON du.idDetailToUsers = c.CommentToArticleIdUser
LEFT JOIN `likes` d ON (d.IdNote = c.idCommentToArticle AND d.LikeType = 6)
GROUP BY c.idCommentToArticle
ORDER BY c.idCommentToArticle DESC
但是让我再解释一下,原始查询中的以下代码选择了前3个idCommentToArticlePID,
(select *
from commenttoarticle g
inner join (select distinct(s.idCommentToArticle)
from commenttoarticle s
order by s.CommentToArticlePID limit 3) as gh)
但是之后因为没有指定ON
,所以3条记录被加入到g
引用的每条记录中。这导致返回完整的数据集。
然后你指定WHERE c.CommentToArticleIdArticle = 11
这会将结果集再次过滤回来,看起来是正确的。
当您添加ON
时(根据@ RADAR的建议),内部查询不包含与WHERE c.CommentToArticleIdArticle = 11
过滤器匹配的任何值,因此您丢失了所有结果。如果您将此过滤器移动到如上所示的内部查询中,那么这些将一起工作而不会发生冲突。
在JOIN
条件下,您表明您需要匹配的文章及其父项,因此我将两者都添加到内部查询的返回中,并在连接条件中检查。
此外,我认为整个g
表引用是多余的,可以删除。您应该能够以c
直接访问此表。
我对GROUP BY
和COUNT (c.idCommentToArticle)
也有一些担忧 - 似乎有点奇怪,但我没有支持上下文(即数据示例),因此它们可能是正确的。如果您仍然遇到问题,我会将GROUP BY
和COUNT
语句发表评论,并在重新添加这些语句之前进行测试以查看您获得的数据。