我正在尝试将这个“虚构的”表格分组(几个连接的结果,如果是)
表,它是怎样的:
ProductID PriceForOneYear PriceForTwoYears PriceForThreeYears PriceForFourYears PriceForFiveYears
1 1.00 NULL NULL NULL NULL
1 NULL 1.50 NULL NULL NULL
1 NULL NULL 2.00 NULL NULL
1 NULL NULL NULL 2.50 NULL
1 NULL NULL NULL NULL 3.00
2 5.00 NULL NULL NULL NULL
2 NULL 5.50 NULL NULL NULL
2 NULL NULL 6.00 NULL NULL
2 NULL NULL NULL 6.50 NULL
2 NULL NULL NULL NULL 7.00
表,应该如何:
ProductID PriceForOneYear PriceForTwoYears PriceForThreeYears PriceForFourYears PriceForFiveYears
1 1.00 1.50 2.00 2.50 3.00
2 5.00 5.50 6.00 6.50 7.00
NULL应该失效。
有什么想法吗?
到目前为止我尝试了“GROUP BY ..”和GROUP_CONCATE(DISTINCT ..)。
创建我的“虚构表”的查询:
SELECT
`tblproducts`.`id` AS `productid`,
IF(`tblproductconfigoptionssub`.`optionname` = '1', `tblpricing`.`monthly`, NULL) AS `priceforoneyear`,
IF(`tblproductconfigoptionssub`.`optionname` = '2', ROUND(`tblpricing`.`monthly` / 2, 2), NULL) AS `pricefortwoyears`,
IF(`tblproductconfigoptionssub`.`optionname` = '3', ROUND(`tblpricing`.`monthly` / 3, 2), NULL) AS `priceforthreeyears`,
IF(`tblproductconfigoptionssub`.`optionname` = '4', ROUND(`tblpricing`.`monthly` / 4, 2), NULL) AS `priceforfouryears`,
IF(`tblproductconfigoptionssub`.`optionname` = '5', ROUND(`tblpricing`.`monthly` / 5, 2), NULL) AS `priceforfiveyears`
FROM `tblproducts` INNER JOIN `tblproductconfigoptionssub` ON `tblproducts`.`id` = `tblproductconfigoptionssub`.`configid` INNER JOIN `tblpricing` ON `tblproductconfigoptionssub`.`id` = `tblpricing`.`relid` WHERE `tblproducts`.`gid` = '1' AND `tblpricing`.`type` = 'configoptions';
答案 0 :(得分:1)
将查询更改为聚合查询,并在列上使用max()
:
SELECT `tblproducts`.`id` AS `productid`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '1', `tblpricing`.`monthly`, NULL)) AS `priceforoneyear`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '2', ROUND(`tblpricing`.`monthly` / 2, 2), NULL)) AS `pricefortwoyears`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '3', ROUND(`tblpricing`.`monthly` / 3, 2), NULL)) AS `priceforthreeyears`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '4', ROUND(`tblpricing`.`monthly` / 4, 2), NULL)) AS `priceforfouryears`,
max(IF(`tblproductconfigoptionssub`.`optionname` = '5', ROUND(`tblpricing`.`monthly` / 5, 2), NULL)) AS `priceforfiveyears`
FROM `tblproducts` INNER JOIN
`tblproductconfigoptionssub`
ON `tblproducts`.`id` = `tblproductconfigoptionssub`.`configid` INNER JOIN
`tblpricing`
ON `tblproductconfigoptionssub`.`id` = `tblpricing`.`relid`
WHERE `tblproducts`.`gid` = '1' AND `tblpricing`.`type` = 'configoptions'
GROUP BY `tblproducts`.`id`;