Reputation: 12399
The following request gives me a list of products, the stores that sells them and the "parent" store , which I need for other purposes:
SELECT `allproducts`.`id_store` , `uniques` . *
FROM `uniques`
INNER JOIN `allproducts` ON `allproducts`.`SKU` = `uniques`.`SKU`
Result is as follows :
id_store SKU id_parent name sale_sdate sale_edate
1085 100768 1088 productA 5/18/2014 6/14/2014
1088 100768 1088 productA 5/18/2014 6/14/2014
1089 100768 1088 productA 5/18/2014 6/14/2014
You can see that on the second line, the id_store and id_parent are the same (parent store sells the product too). In this case, I should replace the id_parent with a 0 like so :
id_store SKU id_parent name sale_sdate sale_edate
1085 100768 1088 productA 5/18/2014 6/14/2014
1088 100768 0 productA 5/18/2014 6/14/2014
1089 100768 1088 productA 5/18/2014 6/14/2014
I am having a really hard time integrating the IF condition in this big request (I can post here all the things I tried but it might make things very confusing). Could anyone help?
Upvotes: 2
Views: 3683
Reputation: 18757
Use CASE
. And remove the WHERE
clause if there is no other conditions.
SELECT `allproducts`.`id_store`, `uniques`.SKU,
CASE WHEN `allproducts`.`id_store`=`uniques`.`id_parent` THEN 0 ELSE `uniques`.`id_parent` END as id_parent,
`uniques`.`name`,`uniques`.`sale_sdate`,`uniques`.`sale_edate`
FROM `uniques`
INNER JOIN `allproducts` ON `allproducts`.`SKU` = `uniques`.`SKU`
Explanation:
If id_store
is equal to id_parent
, it will select 0. Otherwise, it will select id_parent
itself.
EDIT:
I would like to rewrite your query with alias names for better readability.
SELECT ap.`id_store`, u.SKU,
CASE WHEN ap.`id_store`=u.`id_parent` THEN 0 ELSE u.`id_parent` END as id_parent,
u.`name`,u.`sale_sdate`,u.`sale_edate`
FROM `uniques` u
INNER JOIN `allproducts` ap ON ap.`SKU` = u.`SKU`
Upvotes: 6
Reputation: 21757
Use the if
like this:
SELECT a.`id_store`, a.`SKU`,
IF (a.`id_store` = u.`id_store`, 0, u.id_store`) as `id_parent`,
u.`name`, u.`sale_sdate`, `u.sale_edate`
FROM `uniques` u
INNER JOIN `allproducts` a ON u.`SKU` = a.`SKU`
The WHERE
clause can be removed since you specify the fields to join on in your INNER JOIN
clause.
Upvotes: 2