SELECT p1.last_name, p1.first_name, p1.city, p1.state
FROM president AS p1 INNER JOIN president AS p2
ON p1.city = p2.city AND p1.state = p2.state
WHERE (p1.last_name <> p2.last_name OR p1.first_name <> p2.first_name)
ORDER BY state, city, last_name;
正如剧本所说,它应该显示具有相同城市和州的不同名称值。 然后将忽略来自p1和p2的相同名字或姓氏。
但是我在输出上得到了这个。
last_name first_name City State
--------------------------------------------
'Adams', 'John Quincy', 'Braintree', 'MA'
'Adams', 'John', 'Braintree', 'MA'
'Obama', 'Barack', 'New York', 'NY'
'Roosevelt', 'Theodore', 'New York', 'NY'
'Bush', 'George', 'Westmoreland', 'VA'
'Bush', 'George', 'Westmoreland', 'VA'
'Monroe', 'James', 'Westmoreland', 'VA'
'Monroe', 'James', 'Westmoreland', 'VA'
'Washington', 'George', 'Westmoreland', 'VA'
'Washington', 'George', 'Westmoreland', 'VA'
它显示了乔治布什,詹姆斯门罗和乔治华盛顿的两个价值观。我检查了我的数据库,我很肯定这些名称没有其他重复值。
答案 0 :(得分:1)
最简单的解决方案是简单的DISTINCT
SELECT DISTINCT p1.last_name, p1.first_name, p1.city, p1.state
FROM president AS p1 INNER JOIN president AS p2
ON p1.city = p2.city AND p1.state = p2.state
WHERE (p1.last_name <> p2.last_name OR p1.first_name <> p2.first_name)
ORDER BY state, city, last_name;
(所有选定字段的分组产生相同的结果,但可读性较差且维护较少。)
答案 1 :(得分:0)
在比较名字和姓氏的值时,尝试在查询中使用TRIM
SELECT p1.last_name, p1.first_name, p1.city, p1.state
FROM president AS p1 INNER JOIN president AS p2
ON p1.city = p2.city AND p1.state = p2.state
WHERE (TRIM(p1.last_name) <> TRIM(p2.last_name) OR TRIM(p1.first_name) <> TRIM(p2.first_name))
ORDER BY state, city, last_name;
答案 2 :(得分:-2)
为什么不对记录进行分组?
SELECT p1.last_name, p1.first_name, p1.city, p1.state
FROM president AS p1 INNER JOIN president AS p2
ON p1.city = p2.city AND p1.state = p2.state
WHERE (p1.last_name <> p2.last_name OR p1.first_name <> p2.first_name)
GROUP BY p1.last_name, p1.first_name, p1.city, p1.state
ORDER BY state, city, last_name