MySQL&或&条件

2022-08-05 00:00:00 select conditional-statements php mysql

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

解决方案

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

相关文章