0

我有一个使用 WHERE 子句的查询。

我的查询:

SELECT * FROM notifications WHERE recipient= '".$_SESSION['id']."' AND viewed >  
'".$twoweeksago."' OR viewed IS NULL ORDER BY recieved DESC

基本上,查询选择收件人是登录用户并且查看的日期不到两周的所有数据行($twoweeksago 是我脚本中设置的变量)。但是,查看列的默认值是 0000-00-00 00:00:00 所以我不得不使用:

OR viewed IS NULL

这就产生了一个问题。我认为这是一个仅适用于前一个条件的条件,即:

 AND viewed > '".$twoweeksago."'

但是,它实际上是整个 WHERE 子句的 OR,并且使所有先前的条件无效。如何编写仅影响 AND 查看的 OR 条件 > '".$twoweeksago."'

谢谢!

4

6 回答 6

1

您应该将条件括在括号中,如下所示:

SELECT * FROM notifications WHERE recipient= '".$_SESSION['id']."' AND (viewed > '".$twoweeksago."' OR viewed IS NULL) ORDER BY recieved DESC

这应该有效。

作为旁注,您应该记住不要直接使用用户的变量,因为它会引入安全漏洞。

于 2013-07-09T18:15:44.217 回答
0

您应该在分组子句周围添加括号:

SELECT * FROM notifications WHERE recipient= '".$_SESSION['id']."' AND (viewed >  '".$twoweeksago."' OR viewed IS NULL) ORDER BY recieved DESC
于 2013-07-09T18:14:01.330 回答
0
SELECT * FROM notifications WHERE recipient= '".$_SESSION['id']."' AND (viewed IS NULL OR viewed > '".$twoweeksago."') ORDER BY recieved DESC

我相信这会奏效。

于 2013-07-09T18:14:08.467 回答
0
SELECT * FROM notifications
WHERE recipient= '" . $_SESSION['id'] . "'
AND (
    viewed > '" . $twoweeksago . "'
    OR viewed IS NULL
)
ORDER BY recieved DESC;
于 2013-07-09T18:14:27.180 回答
0

试试这个

SELECT * FROM notifications WHERE recipient= '".$_SESSION['id']."' AND (viewed >  
'".$twoweeksago."' OR viewed=NULL ORDER BY recieved DESC
于 2013-07-09T18:15:33.730 回答
0
SELECT *
FROM table
WHERE
receipt = session
HAVING
viewed > time OR
viewed = null
ORDER BY
sort DESC

使用 Pdo 您的示例将如下所示。

$link = new PDO('mysql:host=localhost;dbname=db', 'User', 'Pass');
$entry = $link->prepare('SELECT * FROM table WHERE receipt = :session HAVING viewed > :time OR viewed = null ORDER BY received DESC');
$entry->execute(array('session' => $Session, 'time' => $Time));

更容易阅读,更不用说。现在你有更多的控制更少的混乱能力。:3 PDO 赢得任何人?

于 2013-07-09T18:26:10.853 回答