我有一个非常复杂的SQL语句,想要添加一个WHERE子句,该子句仅在hidden
列不是'1'的情况下选择结果,但是它需要与特定用户相关。
i.e,如果表1中的hidden
为1且userid
为1,我不想得到这个结果。但是,由于该表中没有用户2的记录,我希望他们看到它。
到目前为止,这是我设法完成的工作:
$where .= " AND uh.hidden IS NULL ";
但是,如果我以用户2身份登录,则看到的结果与用户1相同。
如何做到这一点,结果也可以根据用户显示?
SQL查询:
$pdo = new PDO('mysql:host=localhost;dbname=myDB', 'root', 'root');
$select = 'SELECT tl.id,
tl.name,
tl.locale,
ROUND(AVG(pr.rating),0) AS rating ';
$from = ' FROM theList AS tl ';
$join = ' LEFT JOIN post_rating AS pr ON tl.id = pr.postid ';
$join2 = ' LEFT JOIN user_hidden_list AS uh ON uh.est_id = tl.id ';
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : [''];
$where = ' WHERE 1 = 1 ';
if (in_array("pub", $opts)) {
$where .= " AND pub = 1";
}
if (in_array("bar", $opts)) {
$where .= " AND bar = 1";
}
$where = ' WHERE uh.hidden IS NULL ';
$group = ' GROUP BY tl.id, tl.name ';
$sql = $select . $from . $join . $join2 . $where . $group;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);