我正在尝试使用动态键过滤数据透视表。
我有 3 个表,定义如下。当我不使用group by
时,我的查询使用一个LEFT JOIN
语句并产生如下结果:
(来源:maverabilisim.com)
黄色条是目标列,蓝色条是过滤条件。
我需要它返回如下所示的内容:
(来源:maverabilisim.com)
使用这样的条件:.... AND v.key_id=1 (color=1)
如何构建 SQL 查询以达到此结果?
我的 SQL 模式/测试数据:
CREATE TABLE `ads` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`ads_title` CHAR(80) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `ads_keys` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`key` CHAR(25) NULL DEFAULT NULL ,
`inlist` INT(1) UNSIGNED ZEROFILL NULL DEFAULT NULL ,
PRIMARY KEY (`id`)
);
CREATE TABLE `ads_values` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`ads_id` INT(3) NULL DEFAULT NULL,
`key_id` INT(10) NULL DEFAULT NULL,
`value` INT(10) NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `ads_id` (`ads_id`, `key_id`)
);
INSERT INTO `ads` VALUES (1, 'AAA');
INSERT INTO `ads` VALUES (2, 'BBB');
INSERT INTO `ads` VALUES (3, 'CCC');
INSERT INTO `ads` VALUES (4, 'DDD');
INSERT INTO `ads` VALUES (5, 'EEE');
INSERT INTO `ads` VALUES (6, 'FFF');
INSERT INTO `ads_keys` VALUES (1, 'KM', 1);
INSERT INTO `ads_keys` VALUES (2, 'OIL', 0);
INSERT INTO `ads_keys` VALUES (3, 'YEAR', 1);
INSERT INTO `ads_keys` VALUES (4, 'COLOR', 0);
INSERT INTO `ads_keys` VALUES (5, 'SPEED', 0);
INSERT INTO `ads_values` VALUES (1, 1, 1, 89000);
INSERT INTO `ads_values` VALUES (2, 1, 2, 200);
INSERT INTO `ads_values` VALUES (3, 1, 3, 2010);
INSERT INTO `ads_values` VALUES (4, 1, 4, 1);
INSERT INTO `ads_values` VALUES (5, 1, 5, 180);
INSERT INTO `ads_values` VALUES (6, 2, 1, 13000);
INSERT INTO `ads_values` VALUES (7, 2, 2, 150);
INSERT INTO `ads_values` VALUES (8, 2, 3, 2008);
INSERT INTO `ads_values` VALUES (9, 2, 4, 1);
INSERT INTO `ads_values` VALUES (10, 2, 5, 160);
INSERT INTO `ads_values` VALUES (11, 3, 1, 79800);
INSERT INTO `ads_values` VALUES (12, 3, 2, 172);
INSERT INTO `ads_values` VALUES (13, 3, 3, 2008);
INSERT INTO `ads_values` VALUES (14, 3, 4, 2);
INSERT INTO `ads_values` VALUES (15, 3, 5, 178);
INSERT INTO `ads_values` VALUES (16, 4, 1, 56781);
INSERT INTO `ads_values` VALUES (17, 4, 2, 127);
INSERT INTO `ads_values` VALUES (18, 4, 3, 2009);
INSERT INTO `ads_values` VALUES (19, 4, 4, 3);
INSERT INTO `ads_values` VALUES (20, 4, 5, 156);
INSERT INTO `ads_values` VALUES (21, 5, 1, 10200);
INSERT INTO `ads_values` VALUES (22, 5, 2, 205);
INSERT INTO `ads_values` VALUES (23, 5, 3, 2000);
INSERT INTO `ads_values` VALUES (24, 5, 4, 3);
INSERT INTO `ads_values` VALUES (25, 5, 5, 160);
INSERT INTO `ads_values` VALUES (26, 6, 1, 45877);
INSERT INTO `ads_values` VALUES (27, 6, 2, 150);
INSERT INTO `ads_values` VALUES (28, 6, 3, 2009);
INSERT INTO `ads_values` VALUES (29, 6, 4, 1);
INSERT INTO `ads_values` VALUES (30, 6, 5, 168);