mysql 互相关注的问题

3 篇文章 0 订阅

第一种方法(郭玉川提供)

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();
  • 具体的实现思路需要分析一下,整理好了再说,先用着
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值