如何计算MySQL中的内连接和多个条件

时间:2015-11-03 03:55:12

标签: mysql join conditional

我希望每次使用每种颜色时都会计算一个查询。

tbl_places是保存来自多个枚举表的数据的主表。 tbl_places保存不同建筑物中特定楼层颜色的相应INT值。 `

tbl_paintcolor是一个包含2列的枚举表:value和color。

我不知道如何将ON子句与我想在tbl_places中计算的特定列相关联。

SELECT
  `tbl_paintcolor`.`Color` AS Paint_Color,
  count(`tbl_places`.`blg1floor1_color`) AS Blg1Floor1,
  count(`tbl_places`.`blg1floor2_color`) AS Blg1Floor2,
  count(`tbl_places`.`blg1floor3_color`) AS Blg1Floor3
FROM `tbl_places` 
INNER JOIN `tbl_paintcolor` ON (`tbl_places`.`blg1floor1_color`=`tbl_paintcolor`.`Value` OR `tbl_places`.`blg1floor2_color`=`tbl_paintcolor`.`Value`)
GROUP BY `tbl_paintcolor`.`Color`

此查询最终会或多或少地计算同一列。

如何将ON子句中的条件表达式与我想在SELECT子句中计数的列相关联?

我希望查询为每个特定楼层输出一列,每行计算找到颜色的次数。此查询的输出结构为:

╔════════╦════════════╦════════════╦════════════╗
║ Color  ║ Blg1Floor1 ║ Blg1Floor2 ║ Blg1Floor3 ║ etc...
╠════════╬════════════╬════════════╬════════════╣
║ red    ║     23     ║     23     ║     23     ║
║ orange ║     23     ║     23     ║     23     ║
║ yellow ║     23     ║     23     ║     23     ║
╚════════╩════════════╩════════════╩════════════╝

感谢您的时间,如果不清楚,请道歉,我对SQL很新。

2 个答案:

答案 0 :(得分:1)

我认为你应该尝试用SUM替换COUNT

SELECT
    `tbl_paintcolor`.`Color` AS Paint_Color,
    SUM(IF(`tbl_places`.`blg1floor1_color`=`tbl_paintcolor`.`Value`, 1, 0)) AS Blg1Floor1,
    SUM(IF(`tbl_places`.`blg1floor2_color`=`tbl_paintcolor`.`Value`, 1, 0)) AS Blg1Floor2,
    SUM(IF(`tbl_places`.`blg1floor3_color`=`tbl_paintcolor`.`Value`, 1, 0)) AS Blg1Floor3,
FROM `tbl_places` 
INNER JOIN `tbl_paintcolor` ON (
        `tbl_places`.`blg1floor1_color`=`tbl_paintcolor`.`Value` 
        OR `tbl_places`.`blg1floor2_color`=`tbl_paintcolor`.`Value`
        OR `tbl_places`.`blg1floor3_color`=`tbl_paintcolor`.`Value`
)
GROUP BY `tbl_paintcolor`.`Color`

或您可以尝试的另一种方式是

SELECT `tbl_paintcolor`.`Color` AS Paint_Color,
    (SELECT COUNT(1) AS qty FROM `tbl_places` p1  WHERE p1.`blg1floor1_color`=`tbl_paintcolor`.`Value`) AS Blg1Floor1,
    (SELECT COUNT(1) AS qty FROM `tbl_places` p2  WHERE p2.`blg1floor2_color`=`tbl_paintcolor`.`Value`) AS Blg1Floor2,
    (SELECT COUNT(1) AS qty FROM `tbl_places` p3  WHERE p3.`blg1floor3_color`=`tbl_paintcolor`.`Value`) AS Blg1Floor3
FROM `tbl_paintcolor`

答案 1 :(得分:0)

SUM()

CASE WHEN可以解决问题。

SELECT
      `tbl_paintcolor`.`Color` AS Paint_Color,
      SUM(CASE WHEN `tbl_places`.`blg1floor1_color` IS NOT NULL THEN 1 ELSE 0 END ) AS Blg1Floor1,
      SUM(CASE WHEN `tbl_places`.`blg1floor2_color` IS NOT NULL THEN 1 ELSE 0 END ) AS Blg1Floor2,
      SUM(CASE WHEN `tbl_places`.`blg1floor2_color` IS NOT NULL THEN 1 ELSE 0 END ) AS Blg1Floor3
    FROM `tbl_places` 
    LEFT JOIN `tbl_paintcolor`
    ON (`tbl_places`.`blg1floor1_color`=`tbl_paintcolor`.`Value`
                               OR `tbl_places`.`blg1floor2_color`=`tbl_paintcolor`.`Value`)
    GROUP BY `tbl_paintcolor`.`Color`

希望这有帮助