按照这个方案,我在它们之间链接了三个表:一栋建筑物有很多语句,其中有很多房间。每个房间的类型都有一个Enum字段(浴室,厨房...)和一个区域。
以下是SQL代码:
CREATE TABLE `test_building` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`flags` int(10) unsigned NOT NULL DEFAULT '0',
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`residence_id` int(10) unsigned NOT NULL DEFAULT '0',
`status` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `residence_id` (`residence_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `test_settlement` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`building_id` int(10) unsigned NOT NULL DEFAULT '0',
`flags` int(10) unsigned NOT NULL DEFAULT '0',
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`residence_id` int(10) unsigned NOT NULL DEFAULT '0',
`status` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `building_id` (`building_id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `test_room` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`settlement_id` int(10) unsigned NOT NULL DEFAULT '0',
`flags` int(10) unsigned NOT NULL DEFAULT '0',
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`type` ENUM('Chambre', 'Cuisine', 'WC', 'Salon', 'Salle de bain') NOT NULL,
`area` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `settlement_id` (`settlement_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
目标是将2栋建筑物的清单存储在2D php数组中,并按类型将每个建筑物的面积总和存储。
以最终数组为例,应如下图所示:
Array(
[Building 1] => array(
[KitchensArea] => 52
[BathrromsAreas] => 43
)
[Building 2] => array(
[KitchensArea] => 69
[BathrromsAreas] => 74
)
)
关于如何做到这一点的任何想法?我就像完全被卡住了,我认为只有一个查询是可能的,但是我真的不介意是否需要很多查询。
谢谢!
答案 0 :(得分:0)
在您的SQL中创建两个名为
的列Is_kitchen使用case语句,对于厨房返回1,否则返回0。
然后是同一个想法的浴室。
然后通过构建这两列的总和来分组
答案 1 :(得分:0)
catcon 提出的 CASE WHEN语句是一件好事。如果有人想知道这里是最终查询。
SELECT test_building.name,
SUM(CASE WHEN test_room.type = "Cuisine" THEN test_room.area ELSE 0 END) AS superficie_cuisine,
SUM(CASE WHEN test_room.type = "Salle de bain" THEN test_room.area ELSE 0 END) AS superficie_salle_de_bain,
SUM(CASE WHEN test_room.type = "Chambre" THEN test_room.area ELSE 0 END) AS superficie_chambre,
SUM(CASE WHEN test_room.type = "WC" THEN test_room.area ELSE 0 END) AS superficie_wc,
SUM(CASE WHEN test_room.type = "salon" THEN test_room.area ELSE 0 END) AS superficie_salon
FROM test_building JOIN test_settlement ON test_settlement.building_id = test_building.id
JOIN test_room ON test_room.settlement_id = test_settlement.id
GROUP BY test_building.name
感谢您的帮助!