1

我有 3 个字段

PId Name Address 
1    aaaa   1234
2    bbbb   4567
3    cccc   1234
4    dddd   4567

我的查询是

SELECT DISTINCT s.Name,ss.Name From Students s INNER JOIN Students ss ON s.PId!=ss.PId WHERE s.Address = ss.Address GROUP BY s.Name,ss.Name

我想得到地址相同的名字,但我是这样的

aaaa cccc
bbbb dddd
cccc aaaa
dddd bbbb

而且我要

aaaa cccc
bbbb dddd 

只要

4

2 回答 2

2

这是否有效:

SELECT
    s.Name,
    ss.Name
FROM
    Students s
INNER JOIN
    Students ss ON s.PId != ss.PId
WHERE
    s.Address = ss.Address
AND
    s.Name < ss.Name
GROUP BY
    s.Name,
    ss.Name

?

如果名称对行是唯一的,您还可以编写:

SELECT
    s.Name,
    ss.Name
FROM
    Students s
INNER JOIN
    Students ss ON s.PId != ss.PId
WHERE
    s.Address = ss.Address
AND
    s.Name < ss.Name
于 2013-06-25T04:21:04.750 回答
2

更短

   SELECT
   s.Name,
  ss.Name
FROM
    Students s
INNER JOIN
    Students ss ON  s.Address = ss.Address 
    and s.PId != ss.PId 
where s.name<ss.name

或者

SELECT
   s.Name  ,
  ss.Name
FROM
    Students s
INNER JOIN
    Students ss ON  s.Address = ss.Address 
    and s.PId != ss.PId 
    and s.name<ss.name

group by 是不必要的

于 2013-06-25T06:53:25.230 回答