我正在开展一项小型社交网络服务。
非常经典,我有3张桌子:
- 表“circles_users”:属于同一“圈子”的所有用户
- 表“朋友”:用户之间的友谊关系
- 表“checkin”:用户是否在某处“签到”
这里是数据库的结构:http://sqlfiddle.com/#!2/27888/1
我想问我的数据库给我:
来自特定“圈子”的所有用户,每个用户:
- 此用户与用户ID = 3 相同的朋友数量
- 如果此用户签到或不签字
这是我要做的事情:
SELECT a.uid,
(
SELECT COUNT(*)
FROM (SELECT IF (uid1 = 3, uid2, uid1) AS cf FROM friends WHERE (friends.uid1 = 3 OR friends.uid2 = 3 )) as b
JOIN friends ON ((friends.uid1 = b.cf AND friends.uid2 = a.uid) OR (friends.uid1 = a.uid AND friends.uid2 = b.cf))
) as common_friends,
checkin.status as checkin_status
FROM
(SELECT circles_users.uid FROM circles_users WHERE circles_users.circlename = 'circle_A') as a
LEFT JOIN checkin ON checkin.uid = a.uid
我收到此错误消息:'on clause'中的未知列'a.uid'
现在已经有2天了,我正试图解决这个问题。
似乎无法在我的子查询中引用相关名称 例如,如果我用特定的uid替换子查询中的 a.uid (例如让我们说'4'),我不会收到任何错误。但当然,结果是错误的......
有人可以帮助我吗?
那将是非常好的:)
其他选择如何?
另一种选择是将“common_friends”子查询作为连接传递
我试着做这样的事情:
SELECT a.uid,
c.cnt as common_friends,
checkin.status as checkin_status
FROM
(SELECT circles_users.uid as uid FROM circles_users WHERE circles_users.circlename = 'circle_A') as a
LEFT JOIN
(
SELECT DISTINCT COUNT(*) as cnt
FROM (SELECT IF (uid1 = 3, uid2, uid1) AS cf FROM friends WHERE (friends.uid1 = 3 OR friends.uid2 = 3 )) as b
JOIN friends ON ((friends.uid1 = b.cf AND friends.uid2 = a.uid) OR (friends.uid1 = a.uid AND friends.uid2 = b.cf))
) as c ON 1=1
LEFT JOIN checkin ON checkin.uid = a.uid
但是:我收到此错误消息:'on clause'中的未知列'a.uid'
无论如何,你认为这个版本会更容易处理,并会为解决我的问题开辟新的可能性吗?
如果你想玩我的疑问:(感谢@zundarz)
答案 0 :(得分:1)
根据您提供的信息和您要查找的信息重新编写查询。
SELECT cu.uid, COUNT(f.uid1) common_friends, c.status
FROM circles_users cu
LEFT JOIN friends f
ON (f.uid1 = cu.uid OR f.uid2 = cu.uid)
AND f.status = "on"
AND IF (f.uid1 = cu.uid, f.uid2, f.uid1) IN (
SELECT IF (uid1 = 3, uid2, uid1)
FROM friends
WHERE status = "on"
AND (friends.uid1 = 3 OR friends.uid2 = 3)
)
LEFT JOIN checkin c
ON c.uid = cu.uid AND c.status = "on"
WHERE cu.circlename = "circle_A"
GROUP BY cu.uid