我有3张表来存储人们对喜欢和不喜欢的兴趣:pages
,pages_likes
,pages_dislikes
现在我希望有一个主页面来显示一个随机页面,但只有那些没有被用户喜欢或不喜欢的页面。
这是我的SQL语句:
SELECT p.id AS page_id, d.uid AS duid, l.uid AS luid, p.title FROM pages p
JOIN pages_dislikes d on d.page_id = p.id JOIN pages_likes l on l.page_id = p.id
WHERE d.uid != '3' AND l.uid != '3' ORDER BY rand() LIMIT 1
但是这仍然显示一个被喜欢或不喜欢的页面,因为有其他用户喜欢或不喜欢这样的页面:
我怎样才能显示特定用户ID尚未喜欢或不喜欢的网页?
答案 0 :(得分:1)
您的查询应该是:
SELECT
p.id AS page_id
,d.uid AS duid
,l.uid AS luid
,p.title FROM pages p
LEFT JOIN pages_dislikes d on d.page_id = p.id
LEFT JOIN pages_likes l on l.page_id = p.id
WHERE (d.page_id IS null OR l.page_id is null) AND d.uid != '3' AND l.uid != '3'
ORDER BY rand() LIMIT 1
您也可以尝试此查询:
SELECT P.pageid, P.pagename FROM Pages P LEFT JOIN
(
SELECT pageid FROM lik WHERE uid <> 3
UNION
SELECT pageid FROM dis WHERE uid <> 3
) LikesDislikes ON LikesDislikes.pageid = P.pageid
ORDER BY rand() LIMIT 1