我在自我加入方面遇到了问题。
我有下表:
CREATE TABLE `test`.`tableN` (
`id` int(10) unsigned NOT NULL auto_increment,
`Group` int(10) unsigned NOT NULL,
`Item` int(10) unsigned NOT NULL,
`data` varchar(45) default NULL,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB;
INSERT INTO `test`.`tableN` (`Group`,`Item`,`data`)
VALUES
(1,100,'aaa'),
(1,200,'bbb'),
(2,100,'ccc'),
(2,200,'ddd'),
(3,100,'eee');
我当时需要做的是运行一个查询,在一行中输出每个“项目”的数据。
我得到的查询是:
SELECT
t1.`Group`,
t1.`item`,
t1.`data`,
t2.`item`,
t2.`data`
FROM tableN t1
LEFT JOIN tableN t2 ON t2.`group`=t1.`group`
WHERE 1=1
AND t1.item = 100
AND t2.item = 200
GROUP BY t1.`Group`;
问题是,这只返回2行(组1和组2)。我需要它也为Group = 3返回一行,即使item = 200没有条目。
我该怎么办呢。
答案 0 :(得分:2)
摆脱你的where子句,将它们全部移到左边的连接中:
SELECT
t1.`Group`,
t1.`item`,
t1.`data`,
t2.`item`,
t2.`data`
FROM `test`.`tableN` AS t1
LEFT JOIN `test`.`tableN` t2 ON t2.`group`=t1.`group` AND t1.item = 100 AND t2.item = 200
GROUP BY t1.`Group`;
编辑:如果只是小组匹配,这当然也会让你排成一行,100和200都不等于t1(或t2)
答案 1 :(得分:1)
SELECT `GROUP`,
MAX(CASE WHEN Item = 100 THEN data END) Item100,
MAX(CASE WHEN Item = 200 THEN data END) Item200
FROM TableN
WHERE Item IN (100, 200)
GROUP BY `GROUP`
输出
╔═══════╦═════════╦═════════╗
║ GROUP ║ ITEM100 ║ ITEM200 ║
╠═══════╬═════════╬═════════╣
║ 1 ║ aaa ║ bbb ║
║ 2 ║ ccc ║ ddd ║
║ 3 ║ eee ║ (null) ║
╚═══════╩═════════╩═════════╝
答案 2 :(得分:1)
将t2.item = 200条件放入JOIN子句。
SELECT
t1.`Group`,
t1.`item`,
t1.`data`,
t2.`item`,
t2.`data`
FROM tableN t1
LEFT JOIN tableN t2 ON t2.`group`=t1.`group` AND t2.item = 200
WHERE 1=1
AND t1.item = 100
GROUP BY t1.`Group`;