1

我有如下查询:

SELECT
    c.id, 
c.user,
c1.user,
c2.user
FROM (
    SELECT 
    id,
    user
    FROM 
        table_x
) c
INNER JOIN table_x c1 ON c.id = c1_id AND c.user = 'steve'
INNER JOIN table_x c2 ON c.id = c2.id AND c1.user = 'rob'
INNER JOIN table_x c3 ON c.id = c3.id AND c2.user LIKE 'r%'
GROUP BY c.id, c.user, c1.user, c2.user

它可以产生如下结果集:

id | user | user | user
1    steve  rob    rob52
1    steve  rob    rob

我需要结果集不包括跨两列的用户不唯一的第二行。有没有办法在不使用 where 子句检查每个单独的列组合的情况下检查这一点?因为当结果集跨越到 6 列时,检查起来就太多了。

结果集也有可能返回为:

id | user | user | user
1    rob    steve  rob

因此,在连接时与<>or!=运算符进行比较不会捕获这样的行,但可以捕获上述结果集中的第 2 行。

谢谢

4

2 回答 2

1

你可以使用distinct on

SELECT DISTINCT ON (c.id, c.user, c1.user)
    c.id, 
c.user,
c1.user,
c2.user
FROM (
    SELECT 
    id,
    user
    FROM 
        table_x
) c
INNER JOIN table_x c1 ON c.id = c1_id AND c.user = 'steve'
INNER JOIN table_x c2 ON c.id = c2.id AND c1.user = 'rob'
INNER JOIN table_x c3 ON c.id = c3.id AND c2.user LIKE 'r%'
GROUP BY c.id, c.user, c1.user, c2.user

这样,对于 distinct on 子句中提到的列的每个不同组合,您只会获得 1 条记录

于 2014-01-01T16:44:17.530 回答
0

有什么问题:

WHERE c.user <> c1.user AND  c1.user <> c2.user AND c2.user <> c.user

这似乎完全符合您的要求。我觉得你多虑了你的问题......

于 2014-08-17T10:55:13.257 回答