使用笛卡尔积的SQL查询出现问题

时间:2008-11-12 10:38:09

标签: sql tsql

我正在努力创建一个查询。它与一个庞大而复杂的数据库有关,但为了这篇文章,我把这个问题简化为更简单的问题。

我有三个表X,Y,Z定义为

CREATE TABLE [dbo].[X](
  [ID] [bigint] NOT NULL
)

CREATE TABLE [dbo].[Y](
  [ID] [nchar](10) NOT NULL
)

CREATE TABLE [dbo].[Z](
  [IDX] [bigint] NOT NULL,
  [IDY] [nchar](10) NOT NULL
)

它们包含以下数据

Table X    Table Y    Table Z
ID         ID         IDX  IDY
--         --         ---  ---
1          A          1    A         
2          B          1    B         
3          C          1    A

我想创建一个产生以下结果的查询

Count  IDX  IDY
=====  ===  ===
    2    1    A
    1    1    B
    0    1    C
    0    2    A
    0    2    B
    0    2    C
    0    3    A
    0    3    B
    0    3    C

我最初的想法是

SELECT COUNT(*), X.ID, Y.ID
FROM
  X
  CROSS JOIN Y
  FULL OUTER JOIN Z ON X.ID = Z.IDX AND Y.ID = Z.IDY
GROUP BY X.ID, Y.ID

但事实证明这是错误的。

有什么想法吗?

4 个答案:

答案 0 :(得分:1)

这似乎有效:

SELECT COUNT(*) AS CNT, IDX, IDY
FROM Z
GROUP BY IDX, IDY
UNION
SELECT 0, X.ID, Y.ID
FROM X, Y
WHERE NOT EXISTS (
    SELECT * FROM Z WHERE Z.IDX = X.ID AND Z.IDY = Y.ID
)
ORDER BY CNT DESC

答案 1 :(得分:1)

SELECT
    (SELECT COUNT(*) FROM Z WHERE IDX = X.ID AND IDY = Y.ID),
    X.ID,
    Y.ID
FROM
    X,Y

这是你的答案......为什么你可能想要那个查询,没有线索:)

答案 2 :(得分:0)

SELECT
  COUNT(z.idx) count,
  x.id idx,
  y.id idy
FROM
  (x CROSS JOIN y)
  LEFT JOIN z ON z.idx = x.id AND z.idy = y.id
GROUP BY
  x.id,
  y.id
ORDER BY
  COUNT(z.idx) DESC,
  x.id,
  y.id

答案 3 :(得分:0)

SELECT (SELECT(COUNT(*) FROM Z) AS COUNT, X.ID AS IDX, y.ID AS IDY
FROM X CROSS JOIN Y 
ORDER BY 1 DESC, 2, 3