mysql 互相关注的问题
第一种方法(郭玉川提供)
SELECT u.uid,u.f_uid,1 AS type
FROM pp_user_focus u
INNER JOIN pp_user_focus u1 ON u.uid = u1.f_uid
AND u.f_uid = u1.uid
where u.uid = {$uid}
UNION ALL
SELECT u.uid,u.f_uid,2 AS type
FROM pp_user_focus u
INNER JOIN pp_user_focus u1 ON u.uid = u1.f_uid
AND u.f_uid != u1.uid
where u.uid = {$uid}
- 实现思路就是分块(查询出来是好友的,和单方面关注的),然后再union all到一起,优点 思路清晰 缺点,个人用框架封装的不好实现部分功能(分页)。因为我菜!
第二种方法
SQL:
SELECT
`uid`,
`f_uid`,
`is_friend`
FROM
(
SELECT
a.uid,
a.f_uid,
if(
sum(1) over (partition by feature) > 1,
1,
0
) as is_friend
FROM
(
SELECT
uid,
f_uid,
if(
uid > f_uid,
concat(f_uid, uid),
concat(uid, f_uid)
) as feature
FROM
`pp_user_focus`
) a
) aa
WHERE
`uid` = '15'
LIMIT
0, 10
thinkphp5代码:
$field1 = "uid,f_uid,if(uid > f_uid, concat(f_uid, uid), concat(uid, f_uid)) as feature";
$build1 = self::field($field1)->buildSql();
$field2 = "a.uid,a.f_uid,if(sum(1) over (partition by feature) > 1, 1, 0) as is_friend";
$build2 = self::table($build1 . ' a')->field($field2)->buildSql();
$field3 = 'uid,f_uid,is_friend';
$data = Db::table($build2 . ' aa ')
->field($field3)
->where('uid', $uid)
->paginate(['page' => $page, 'list_rows' => $per_page])
->toArray();
- 具体的实现思路需要分析一下,整理好了再说,先用着