我创建了两个包含以下记录的表。
CREATE TABLE ForgeRock
(`id` int,`sta` int, `productName` varchar(7), `description` varchar(55));
INSERT INTO ForgeRock
(`id`,`sta`, `productName`, `description`)
VALUES
(1, 0,'OpenIDM', 'Platform for building enterprise provisioning solutions'),
(2,0, 'OpenAM', 'Full-featured access management'),
(3,0, 'OpenDJ', 'Robust LDAP server for Java');
CREATE TABLE ForgeRock1
(`id` int,`sta` int, `productName` varchar(7), `description` varchar(55));
INSERT INTO ForgeRock1
(`id`,`sta`, `productName`, `description`)
VALUES
(1, 2,'hii', 'Platform for building enterprise provisioning solutions'),
(2,0, 'OpenAM', 'Full-featured access management'),
(3,0, 'OpenDJ', 'Robust LDAP server for Java');
我希望联合两个表,但希望记录重复ID为sta = 2
SELECT id,sta
FROM ForgeRock
GROUP BY id
UNION
SELECT id, sta
FROM ForgeRock1
GROUP BY id
结果:
id sta
1 0
2 0
3 0
1 2
预期结果:
id sta
1 2
2 0
3 0
答案 0 :(得分:0)
在 UNION之后进行分组,并使用MAX()选择要为每个组输出的行:
SELECT id, MAX(sta) AS sta
FROM (SELECT id, sta
FROM ForgeRock
UNION
SELECT id, sta
FROM ForgeRock1)
GROUP BY id
ORDER BY id