我有如下查询:
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
因此,在加入时与<>
或!=
运算符的比较不会捕获这样的行,但可能会在上面的结果集中排第2行。
由于
答案 0 :(得分: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条记录答案 1 :(得分:0)
只是出了什么问题:
WHERE c.user <> c1.user AND c1.user <> c2.user AND c2.user <> c.user
这似乎完全符合您的要求。我想你是在思考你的问题......