aamirl
aamirl

Reputation: 1550

MySQL Select: Case When Or Something Else?

First time poster, long-time reader. I have been teaching myself code othe past 6-8 months and I like to think that I am fairly getting decent at the PHP/Javascript/MySQL stack. I definitely love the community that Stack has built because it really helps to share problems with people who understand things a little better.

So my question is probably relatively simple, but I am not sure how to use Case When...Then here. (Or whether that is even correct to use!). Basically what I want to say in my where clause is: if this column = 1, then also process this condition. Something like:

SELECT product_name
FROM b2c_products, b2c_sellers
WHERE b2c_products.productId = b2c_sellers.product_Id AND CASE WHEN b2c_products.productType = 1 THEN b2c_sellers.seller_country = '$country' END;

I hope that gets the idea across - I know this is a simple problem, I just am so new to SQL! Thanks a LOT in advance.

Upvotes: 0

Views: 260

Answers (2)

stefancarlton
stefancarlton

Reputation: 1727

Case statements work don't work in the way you're trying, they mainly for selectors, see http://dev.mysql.com/doc/refman/5.0/en/case.html or staticsan's answer. You can use them in WHERE clauses, but generally it should be considered for data transformation.

MySQL does have the concept of IF statements: http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if which can be nested. For example

1 = IF(b2c_products.productType = 1, IF(b2c_sellers.seller_country = '$country', 1, 0), 0)

As an alternative, you can achieve what you're after with nested with simple AND clauses which will allow you to use indexes too, e.g.

SELECT product_name
FROM b2c_products, b2c_sellers
WHERE ((b2c_products.productType = 1 AND b2c_sellers.seller_country = '$country')
   OR b2c_products.productType <> 1);

As a side note, make sure you escape '$country' to avoid SQL injection.

Upvotes: 1

staticsan
staticsan

Reputation: 30555

Actually, no, what you're trying to do is far from obvious.

CASE is normally used in the fields of a SELECT statement (between SELECT and FROM) to alter the returning data. A simple example might be:

SELECT userid, CASE WHEN disabled = 1 THEN 'Disabled' ELSE '' END AS disabled FROM users;

The way I think of how CASE works is that it runs on every row of output.

Upvotes: 0

Related Questions