1

我有一个简单的 SQL 查询,可以为我提供所有评论过此类图像的用户的信息......

SELECT user.id, user.userName, user.displayName, user.currentDefault, user.discipline
FROM user 
INNER JOIN imageComment ON user.id = imageComment.commentAuthorId
WHERE imageComment.imageAlbumJunctionId = 37 
GROUP BY user.id  
LIMIT 2

LIMIT 2在那里有,因为我知道这张图片只有两条评论。而且我GROUP BY user.id在那里,因为我只想显示有关用户的信息一次,即使他们多次评论。

因此,可以说“迈克”对一张照片发表了两次评论。我的问题是,这个查询...

  1. 因为 , 只搜索 2 条评论LIMIT,然后执行GROUP BY user.id
  2. 执行GROUP BY user.id然后在整个表中搜索第二个唯一用户

我希望这个查询执行#1,因为如果执行#2,它将导致它搜索整个表来寻找第二个用户,而“Mike”实际上是那个同时做了这两个评论的用户。我确实尝试了 anEXPLAIN但我并不真正理解它,因为无论是否存在 aGROUP BY或,它都会给出相同的输出LIMIT。感谢您的阅读。

4

3 回答 3

2

该查询查找评论了图像的前两个用户,所以它是#2。

我建议:

select ...
from user 
where exists 
(
  select * from imageComment 
  where imageComment.commentAuthorId = user.id 
  and imageComment.imageAlbumJunctionId = 37
)

where exists 比内部联接快,因为它可以在第一次之后停止。应该设置好的指标。

于 2013-04-30T06:31:20.910 回答
0

LIMIT在 之后应用GROUP BY user.id。所以在这种情况下,#2 正在发生。但是该WHERE子句将首先过滤表,因此它不会搜索整个表。您的查询将为您提供正确的结果,但我认为这应该更好:

SELECT DISTINCT user.id, user.userName, user.displayName, user.currentDefault, user.discipline
FROM user 
INNER JOIN imageComment ON user.id = imageComment.commentAuthorId
WHERE imageComment.imageAlbumJunctionId = 37 
LIMIT 2
于 2013-04-30T06:31:06.540 回答
0

样品表

User Table                          imageComment Table
id  | userName                      id | commentAuthorId | imageAlbumJunctionId
---------------                     -------------------------------------------
 1  | Mike                           1 | 1               | 37
 2  | John                           2 | 1               | 37
 3  | Carla                          3 | 2               | 37
                                     4 | 3               | 37

关于发生了什么的分裂解释

SELECT user.id, user.userName
FROM user 
INNER JOIN imageComment ON user.id = imageComment.commentAuthorId
WHERE imageComment.imageAlbumJunctionId = 37 

这将返回

 1  | Mike 
 1  | Mike 
 2  | John
 3  | Carla  

在你之后你GROUP BY user.id现在会得到

 1  | Mike 
 2  | John
 3  | Carla 

现在我们使用LIMIT 2并得到

 1  | Mike 
 2  | John
于 2013-04-30T06:45:33.490 回答