0

我遇到了这个 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

4 回答 4

1

您必须将 else 部分添加到您的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'
于 2012-12-09T19:07:57.277 回答
1

MySQLIF语句具有以下语法: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
于 2012-12-09T19:09:02.550 回答
0

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

$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'";
于 2012-12-09T19:08:17.293 回答
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'";
于 2012-12-09T19:13:49.140 回答