我需要3个不同的表来从中提取数据。需要做的是我们从帖子表中提取帖子,其中发布帖子的用户被设置为公共用户,或者如果设置为私人,他们授予访问权限的用户可以查看他们的帖子。
以下是表格:
user: id, username, name, password, email, private
posts: id, title, user, date, state
privateallowed: id, privateuser, alloweduser
这是我的代码,我尝试获取记录:
$username = $_COOKIE['username'];
$sqlposts = "select p.id, u.id, u.private, a.privateuser, a.alloweduser from user u
inner join posts p on u.id = p.user
inner join privateallowed a on a.privateuser = u.id and a.alloweduser = " . $username . "
where u.private='public' or (a.privateuser=p.user and a.alloweduser=" . $username . ")";
$resultpost = mysqli_query($dbcon, $sqlposts);
$numrows = mysqli_num_rows($resultpost);
不幸的是,没有记录被退回。任何帮助或想法都表示赞赏。
答案 0 :(得分:1)
对于它的价值(@pgngp评论需要'" . $username . "'
周围的单引号):
$username = $_COOKIE['username'];
$sqlposts = "SELECT p.id, u.id, u.private, a.privateuser, a.alloweduser
FROM user u
INNER JOIN posts p ON
u.id = p.user
INNER JOIN privateallowed a ON
a.privateuser = u.id AND a.alloweduser = '" . $username . "'
WHERE u.private='public';
$resultpost = mysqli_query($dbcon, $sqlposts);
$numrows = mysqli_num_rows($resultpost)";
另请注意,我已从WHERE
条件中移除了以下内容,因为由于之前的INNER JOIN
而导致其冗余。我们只能推断出这一点,因为您使用了INNER JOIN
,如果您使用了LEFT JOIN
,则需要将条件保留为原样。
. . .or (a.privateuser=p.user and a.alloweduser=" . $username . ")"
说明:
INNER JOIN posts p ON u.id = p.user
u.id = p.user
INNER JOIN privateallowed a ON a.privateuser = u.id
a.privateuser = p.user
AND a.alloweduser = '" . $username . "'
WHERE
答案 1 :(得分:0)
我确实找到了答案,但我确定它不是一个完美的答案。我所做的是将语句分成单独的select语句,然后在where子句中嵌入一个,如下所示:
$sqlposts = "SELECT p.id, u.id, u.private
FROM user u
INNER JOIN posts p ON u.id = p.user
WHERE u.private='public' or p.user in
(
select a.privateuser
from privateallowed a
inner join posts p on p.user = a.privateuser
where a.alloweduser=" . $username . "
)";
我和另一个非常善于使用sql的人看了几个小时,我们无法让select返回正确的结果。我们尝试了以下操作,但由于某种原因,它返回了每个公共用户3次:
SELECT p.id, u.id, u.private
FROM user u
INNER JOIN posts p ON u.id = p.user
INNER JOIN privateallowed a on a.alloweduser=24
WHERE u.private='public' or p.user = a.privateuser
我感谢大家对此的帮助。如果有人有任何其他想法,我很感激他们。我正在一个我希望会增长的网站上工作,我想确保页面尽可能快地加载。