如何在查询的WHERE部分中使用if语句编写SQL查询?

这是我的SQL:

$sql = 'SELECT First, Second,
           Third,Fifth, Status, Isik_id, Comments, Code
    FROM Persons WHERE  Status = 1 && Third = "'.$whoislogged.'" ORDER BY RAND()  LIMIT 1';


Third = "'.$whoislogged.'"是一个来自会话的词。

如果$ whoislogged存在并且等于Third,则查询应类似于:

$sql = 'SELECT First, Second, Third,Fifth, Status, Isik_id, Comments, Code
        FROM Persons
WHERE  Status = 1 && Third = "'.$whoislogged.'" ORDER BY RAND()  LIMIT 1';


但是,如果出现$ whoislogged剂量,则查询应类似于:

 $sql = 'SELECT First, Second,
           Third,Fifth, Status, Isik_id, Comments, Code
    FROM Persons WHERE  Status = 1 ORDER BY RAND()  LIMIT 1';


那么如何将所有这些整合到一个查询中呢?

最佳答案

您可以在查询本身中处理它。

WHERE  Status = 1 and if(Third = "'.$whoislogged.'", Third = "'.$whoislogged.'" , 1=1)


条件部分将检查第三个是否与$ whoislogged匹配,如果正确,则添加id作为条件,否则忽略此条件。

关于php - 如何在WHERE中使用if语句在php中编写SQL查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31804008/

10-13 07:09