Table:
firstname | lastname | age
Joey | Sanchez | 33
Joey | Sanchez | 33
Rachel | Dudok | 28
我试图制作一个返回值的MySQL select语句" ERROR "在2列重复的年龄列中
我尝试了Case语句但它最终只返回1行。
SELECT
Firstname,
Lastname,
CASE
WHEN count(firstname) AND count(lastname) AND count(age) >= 2
THEN '**ERROR**'
ELSE age
END
FROM Table;
答案 0 :(得分:1)
您可以尝试group by
:
select Firstname
, Lastname
, case when count(*) > 1 then '**ERROR**' else age end
from Table
group by Firstname
, Lastname
, age;
或者如果您想要返回包含重复项的所有行:
select t.Firstname
, t.Lastname
, case when (select count(*)
from Table
where Firstname = t.Firstname and
Lastname = t.Lastname and
age = t.age) > 1 then '**ERROR**' else age
end
from Table t
答案 1 :(得分:0)
处理重复记录的方法有很多种。对于大多数情况来说,最好的方法可能是完全使用UNIQUE键来阻止它们:
ALTER TABLE `mytable` ADD UNIQUE INDEX (`firstname`,`lastname`,`age`);
但是,由于您已经有重复项并且需要找到它们,因此以后就可以了。对于您的特定请求,这是一种处理它的方法:
SELECT s.`firstname`,s.`lastname`,IF(c.rc > 1,'ERROR',s.`age`) AS 'age'
FROM `myTable` AS s
JOIN (SELECT `firstname`, `lastname`, `age`, count(*) AS rc
FROM `myTable`
GROUP BY `firstname`,`lastname`,`age`)
AS c ON c.`firstname` = s.`firstname`
AND c.`lastname` = s.`lastname`
AND c.`age` = s.`age`;
如果您只希望每个名称/年龄组合收到1行,请将DISTINCT添加到外部查询中:
SELECT DISTINCT s.`firstname`,s.`lastname`,IF(c.rc > 1,'ERROR',s.`age`) AS 'age'
FROM `myTable` AS s
JOIN (SELECT `firstname`, `lastname`, `age`, count(*) AS rc
FROM `myTable`
GROUP BY `firstname`,`lastname`,`age`)
AS c ON c.`firstname` = s.`firstname`
AND c.`lastname` = s.`lastname`
AND c.`age` = s.`age`;