1

我正在开发一个小型社交网络服务。

非常经典,我有 3 个表:
- 表 “ circles_users” 属于同一个“圈子”的所有用户
- 表“朋友”:用户之间的友谊关系- 表“签到”:用户是否在某处“签到”


这里是数据库的结构: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 子句”中的未知列“a.uid”
现在我已经 2 天尝试修复此问题,但未成功。

似乎无法在我的子查询中引用相关名称。
例如,如果我将子查询中的a.uid替换为特定的 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 子句'中的未知列'a.uid'
无论如何,你认为这个版本会更容易处理并且会为解决我的问题开辟新的可能性吗?


如果你想玩我的查询:(感谢@zundarz)

http://sqlfiddle.com/#!2/27888/1


4

1 回答 1

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

示例sqlFiddle

于 2013-09-25T15:53:46.600 回答