0

I am having a problem with this SQL Statement:

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

I want the SQL statement to work in this way:

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

Any Ideas?

Thanks in advance.

4 Answers 4

1

The MySQL IF statement has the following syntax: IF(condition, expression if true, expression if false).

As far as I can see from your question you are actually looking for a WHERE clause (remember, you can have multiple conditions in WHERE – use boolean operators to combine them):

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, this worked however if it enters 0 is it possible to display a message saying "Out of Stock to the user"
You're probably best of replacing the value 0 with the error string in your frontend. (otherwise: IF(p.FrameNumber = 0, 'Out of stock', p.FrameNumber) FrameNumber
1

You must add an else part to your 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'

Comments

0

You forgot an else part for that IF statement:

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

Comments

0

try this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.