我有一个查询,其中我正在使用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。”'
谢谢!
答案 0 :(得分:1)
您应该将条件包装在这样的括号中:
SELECT * FROM notifications WHERE recipient= '".$_SESSION['id']."' AND (viewed > '".$twoweeksago."' OR viewed IS NULL) ORDER BY recieved DESC
这应该有用。
作为旁注,您应该记住不要直接从用户使用变量,因为它可以引入安全后膛。
答案 1 :(得分:0)
您应该在分组子句周围添加括号:
SELECT * FROM notifications WHERE recipient= '".$_SESSION['id']."' AND (viewed > '".$twoweeksago."' OR viewed IS NULL) ORDER BY recieved DESC
答案 2 :(得分:0)
SELECT * FROM notifications WHERE recipient= '".$_SESSION['id']."' AND (viewed IS NULL OR viewed > '".$twoweeksago."') ORDER BY recieved DESC
我相信这会奏效。
答案 3 :(得分:0)
SELECT * FROM notifications
WHERE recipient= '" . $_SESSION['id'] . "'
AND (
viewed > '" . $twoweeksago . "'
OR viewed IS NULL
)
ORDER BY recieved DESC;
答案 4 :(得分:0)
试试这个
SELECT * FROM notifications WHERE recipient= '".$_SESSION['id']."' AND (viewed >
'".$twoweeksago."' OR viewed=NULL ORDER BY recieved DESC
答案 5 :(得分: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赢得任何人?