一个正确加入的交叉联接

时间:2016-03-09 13:26:38

标签: postgresql join cross-join

我有一张桌子" typl"仅包含2个值:

typl 
------
 COL
 IND

和表"存储"有2列:

achl | typl 
------+------
 AAAA | IND
 AAAA | IND
 AAAA | IND
 AAAA | IND
 AAAA | IND
 AAAA | IND
 BBBB | COL
 BBBB | COL
 BBBB | IND
 BBBB | IND
 BBBB | IND
 BBBB | IND
 BBBB | IND
 BBBB | IND
 BBBB | IND

问题:我可以找到一个查询,对于商店表格中的一组achl,如果只有一个类似于achl =' AAAA',那么所有行都将是交叉加入" typl"表,所以结果将是:

achl | typl 
------+------
 AAAA | COL
 AAAA | COL
 AAAA | COL
 AAAA | COL
 AAAA | COL
 AAAA | COL
 AAAA | IND
 AAAA | IND
 AAAA | IND
 AAAA | IND
 AAAA | IND
 AAAA | IND
 BBBB | COL
 BBBB | COL
 BBBB | IND
 BBBB | IND
 BBBB | IND
 BBBB | IND
 BBBB | IND
 BBBB | IND
 BBBB | IND

2 个答案:

答案 0 :(得分:1)

SELECT 
    * 
FROM store 
WHERE achl IN (
    SELECT achl 
    FROM store
    GROUP BY achl
    HAVING COUNT(DISTINCT typl) = 1
)

答案 1 :(得分:1)

SQL Fiddle

select *
from (
    select achl, typl
    from store
    union all
    select achl, t.typl
    from store s cross join typl t
    where (achl, t.typl) not in (
        select achl, typl
        from store
    )
) s
order by achl, typl