在我的数据库中,我有一个表(喜欢),列出了用户喜欢的项目
在访问用户个人资料时,我需要确定我们共有多少“喜欢”
编写一个能够显示用户之间相互喜欢的查询的最佳方法是什么?
likes table
id | user | item | activated
-----------------------------------
1 | 3 | 14 | 1
2 | 4 | 14 | 1
我需要在此示例中返回 14 。
答案 0 :(得分:1)
假设应该是这样的:
select userViewer.item, items.itemName
from likes userViewer,
likes userProfile,
items
where userProfile.user = $profileUserId
and userViewer.user = $userViewer
and userProfile.item = userViewer.item
and items.item = userViewer.item
其中$ profileUserId - 个人资料用户的userId和$ userViewer - 当前用户的userId
“join on”表单与“items”表相同的查询,例如:
select userViewer.item, items.itemName
from likes userViewer inner join likes userProfile
on userProfile.user = $profileUserId
and userViewer.user = $userViewer
and userProfile.item = userViewer.item
inner join items
on userViewer.item = items.item
答案 1 :(得分:1)
我想知道为什么你没有在where子句
中使用匹配条件SELECT
userViewer.item, items.itemName
FROM
likes AS userViewer
INNER JOIN
likes as userProfile
ON
userProfile.item = userViewer.item
INNER JOIN items
ON
userViewer.item = items.item
WHERE
userViewer.user = $userViewer
AND
userProfile.user = $profileUserId