你想弄清楚这一点,看了很多地方,但由于我的桌子结构,我正在努力。这是我的表结构:
用户 - id,login(pk)
课程 - id(pk),姓名
users_to_lessons - users_LOGIN(fk),lessons_ID(fk)
我如何实施“购买此产品的客户还购买了这个......”功能?
答案 0 :(得分:3)
我真的不明白你的问题以及你需要什么 无论如何,假设您的用户 id = my_user_id 获得 id = my_lesson_id 的课程,并且您想知道获得my_lesson_id的其他用户的所有课程,请尝试以下操作:
SELECT DISTINCT l.id, l.name, COUNT(l.id) as rank
FROM lessons l JOIN users_to_lessons ul
ON l.id = ul.lessons_ID
WHERE l.id<>my_lesson_id AND
ul.users_LOGIN IN
(SELECT DISTINCT us.login FROM users us
JOIN users_to_lessons ls ON us.login = ls.users_LOGIN
WHERE ls.lessons_ID = my_lesson_id
AND us.id<>my_user_id)
GROUP BY l.id
ORDER BY rank DESC, l.name
答案 1 :(得分:1)
尝试以下方法之一:
select
lessons_ID
from
users_to_lessons
where
user_LOGIN IN
(
select
user_LOGIN
from
users_to_lessons
where
lessons_ID = 1
)
AND
lessons_ID <>1
;
select
ul2.lessons_ID
from
users_to_lessons ul1
inner join
users_to_lessons ul2
on
ul1.user_LOGIN = ul2.user_LOGIN
where
ul1.lessons_ID = 1
AND
ul2.lessons_ID <> 1
;