php MySQL“或”条件

u4dcyp6a  于 2022-12-02  发布在  PHP
关注(0)|答案(5)|浏览(144)

看看这个MySQL查询,然后我将向您展示我真正希望它做什么...

mysql_query("
SELECT * FROM Drinks WHERE
    email='$Email'
    AND date='$Date_Today'
    OR date='$Date_Yesterday'
    OR date='$Date_TwoDaysAgo'
    OR date='$Date_ThreeDaysAgo'
    OR date='$Date_FourDaysAgo'
    OR date='$Date_FiveDaysAgo'
    OR date='$Date_SixDaysAgo'
    OR date='$Date_SevenDaysAgo'");

问题是我希望它总是与email匹配。在这种情况下(例如),如果日期等于$Date_SixDaysAgo,那么即使$Email不等于email列,它也会从查询中被选中。
因此,简而言之,我希望电子邮件始终等于电子邮件列,如果查询提取的日期等于$Daye_TwoDaysAgo$Date_ThreeDaysAgo等,但不等于电子邮件,则不要提取它。
我想我的查询看起来会像这样,但我很肯定它不会工作。

mysql_query("
    SELECT * FROM Drinks WHERE
    email='$Email'
    AND date='$Date_Today
    || $Date_Yesterday
    || $Date_TwoDaysAgo
    || $Date_ThreeDaysAgo
    || $Date_FourDaysAgo
    || $Date_FiveDaysAgo
    || $Date_SixDaysAgo
    || $Date_SevenDaysAgo'");
l3zydbqr

l3zydbqr1#

使用括号对OR语句进行分组。

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");

您也可以使用IN

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND date IN ('$Date_Today','$Date_Yesterday','$Date_TwoDaysAgo','$Date_ThreeDaysAgo','$Date_FourDaysAgo','$Date_FiveDaysAgo','$Date_SixDaysAgo','$Date_SevenDaysAgo')");
8e2ybdfx

8e2ybdfx2#

使用括号:

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND 
    (date='$Date_Today' 
     OR date='$Date_Yesterday' 
     OR date='$Date_TwoDaysAgo' 
     OR date='$Date_ThreeDaysAgo' 
     OR date='$Date_FourDaysAgo' 
     OR date='$Date_FiveDaysAgo' 
     OR date='$Date_SixDaysAgo' 
     OR date='$Date_SevenDaysAgo'
    )
");

但是你也应该看一下IN运算符,所以你可以说date IN('$date1','$date2',...')
但是,如果您总是有一组连续的日期,为什么不对日期部分执行以下操作

date <= $Date_Today AND date >= $Date_SevenDaysAgo
f2uvfpb9

f2uvfpb93#

你的问题是关于mysql中的operator precedencesAlex has shown you如何用括号“覆盖”优先级。
但顺便提一下,如果列date的类型是Date,则可以使用MySQL's date and time functions来获取最近七天的记录,例如:

SELECT
  *
FROM
  Drinks
WHERE
  email='$Email'
  AND date >= Now()-Interval 7 day

(or可能是Curdate()而不是Now())

kmynzznz

kmynzznz4#

将AND逻辑括在括号中,如下所示:

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");
zujrkrfu

zujrkrfu5#

试试这个

mysql_query("
SELECT * FROM Drinks WHERE
    email='$Email'
    AND date='$Date_Today'
    OR date='$Date_Yesterday', '$Date_TwoDaysAgo', '$Date_ThreeDaysAgo', '$Date_FourDaysAgo', '$Date_FiveDaysAgo', '$Date_SixDaysAgo', '$Date_SevenDaysAgo'"     
   );

我是这样的

OR date='$Date_Yesterday' oR '$Date_TwoDaysAgo'.........

相关问题