MySQL-IF语句错误

时间:2012-12-09 19:04:04

标签: php mysql sql database

我遇到了这个SQL语句的问题:

$sql="SELECT b.FrameNumber, b.BikeCode, IF(b.ProductID = 0, p.FrameNumber) 
   AS FrameNumber 
 FROM BikeStock b LEFT JOIN Purchase p ON b.FrameNumber = p.FrameNumber 
 WHERE b.bikecode = '$bikecode'";

我希望SQL语句以这种方式工作:

Select FrameNumber & BikeCode from BikeStock 
THEN IF ProductID(BikeStock) is equal to 0 
     then it will grab the framenumber from the purchase table where bikecode is equal to $bikecode

任何想法?

提前致谢。

4 个答案:

答案 0 :(得分:1)

您必须在if()

中添加其他部分
SELECT b.FrameNumber, b.BikeCode,
       IF(b.ProductID = 0, p.FrameNumber, NULL) AS FrameNumber
FROM BikeStock b
LEFT JOIN Purchase p ON b.FrameNumber = p.FrameNumber
WHERE b.bikecode = '$bikecode'

答案 1 :(得分:1)

MySQL IF语句具有以下语法:IF(condition, expression if true, expression if false)

据我所知,你实际上是在寻找一个WHERE子句(请记住,你可以在WHERE中有多个条件 - 使用布尔运算符来组合它们):

SELECT b.FrameNumber, b.BikeCode, p.FrameNumber
FROM BikeStock b
LEFT JOIN Purchase p ON b.FrameNumber = p.FrameNumber
WHERE b.bikecode = :bikecode AND b.ProductID = 0

答案 2 :(得分:0)

您忘记了该IF语句的else部分:

$sql = "SELECT b.FrameNumber, b.BikeCode, IF(b.ProductID = 0, p.FrameNumber, NULL /* ELSE HERE */) AS FrameNumber 
        FROM BikeStock b 
        LEFT JOIN Purchase p 
            ON b.FrameNumber = p.FrameNumber 
        WHERE b.bikecode = '$bikecode'";

答案 3 :(得分:0)

试试这个

    $sql="SELECT b.FrameNumber, b.BikeCode, p.FrameNumber (
          CASE WHEN b.ProductID = 0 THEN p.FrameNumber ELSE NULL END AS Framenumber)  
          FROM BikeStock b 
          LEFT JOIN Purchase p ON b.FrameNumber = p.FrameNumber 
          WHERE b.bikecode = '$bikecode'";