我有一个名为favorites的表,其结构如下:
CREATE TABLE IF NOT EXISTS `favourites` (
`ID` int(11) NOT NULL,
`followerID` int(11) NOT NULL,
`followedID` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=615 DEFAULT CHARSET=latin1;
我有一个网络服务来检索关注我的用户列表。
SELECT ID, followerID, FName, SName , pic
FROM Favourites
INNER JOIN users
ON users.UserID = Favourites.followerID
WHERE followedID = ?
ORDER BY ID Desc
LIMIT ?, 10
其中param传入where条件的是有问题的用户检索他们的关注者列表。
我需要在此响应中添加一个附加字段,以指示我是否也在关注它们。
我最初尝试添加此内容如下,但我收到语法错误。
SELECT ID, followerID, FName, SName, pic, count(SELECT followerid from favourites where followedid = 36) as amFollowing
FROM Favourites
INNER JOIN users
ON users.UserID = Favourites.followerID
WHERE followedID = 36
ORDER BY ID Desc
LIMIT 0, 10
我发现很难理解,如果有人对如何处理这个问题有任何建议吗?我应该添加一个isFollowedBack列并动态更新,还是有一种简单的方法来实现我想要的而不改变表结构?也许我应该使用CASE来动态计算它?
根据Linoff的回答进行更新:
SELECT ID, followerID, FName, SName, pic,
(SELECT COUNT(*) FROM favourites f2 WHERE f2.followedid = f.followerId and f2.followerid = 36 ) as amFollowing
FROM Favourites f
INNER JOIN users u ON u.UserID = f.followerID
WHERE followedID = 36
ORDER BY ID
Desc limit 0, 10
(36是发出请求的人的用户ID)
运行解释返回:
id : 1
select_type : PRIMARY
table : f
type : index
possible_keys : NULL
key : PRIMARY
key_len : 4
ref : NULL
rows : 10
Extra : Using where
id : 1
select_type : PRIMARY
table : u
type : eq_ref
possible_keys : PRIMARY
key : PRIMARY
key_len : 4
ref : DBName.f.followerID
rows : 1
Extra : NULL
id : 2
select_type : DEPENDENT SUBQUERY
table : f2
type : ALL
possible_keys : NULL
key : NULL
rows : 716
Extra : Using where
答案 0 :(得分:0)
您可以将count()
移动到子查询中:
SELECT ID, followerID, FName, SName, pic,
(SELECT COUNT(*)
FROM favourites f2
WHERE f2.followedid = f.followedId
) as amFollowing
FROM Favourites f INNER JOIN
users u
ON u.UserID = f.followerID
WHERE followedID = 36
ORDER BY ID Desc
LIMIT 0, 10;
您还应养成在查询中使用表别名和限定列名的习惯。