MySQL “Or” 条件

2022-08-30 15:09:03

看看这个查询,然后我会告诉你我真正想要它做什么...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'");

它的问题在于我希望它始终与电子邮件匹配。在这种情况下(例如),如果日期等于,则即使不等于电子邮件列,也会从查询中选择它。$Date_SixDaysAgo$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'");

答案 1

使用方括号对 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')");

答案 2

使用括号:

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'
    )
");

但是您还应该看看操作员。所以你可以说“日期在('$date 1','$date 2',...)`IN

但是,如果您总是有一组连续的日子,为什么不对日期部分执行以下操作

date <= $Date_Today AND date >= $Date_SevenDaysAgo

推荐