2015-11-03 91 views
0

我想要一個查詢,每次使用每種顏色時都會計數。如何計算MySQL中的內部連接和多個條件

tbl_places是保存來自幾個枚舉表的數據的主表。 tbl_places爲不同建築物中特定樓層的顏色保留相應的INT值。 `

tbl_paintcolor是一個包含2列的枚舉表:值和顏色。

我不知道如何將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。

+0

您的查詢不罷工我是錯的。你目前的產出是多少? –

+0

它爲每列輸出相同的計數。我認爲我的問題在OR語句中。我正在尋找一種更好的方法來將ON子句鏈接到我的SELECT子句 –

+0

如果您向我們展示數據和查詢輸出的可重複示例,可能會有所幫助。 –

回答

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` 

希望這有助於

+0

謝謝@Subin!這對我有用。 –

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` 
+0

感謝@David,您的第一個腳本對我更好,因爲我有日期列,並且我可以使用where子句來聚焦查詢 –