4

我有一个复杂的问题。我将尝试用示例来解释它:

有一个表有主键,我想加入另一个表,第一个表的主键是外键,我想如果在第二个表中有重复的外键来选择重复性的数量。例如:

第一张表:

  id    name 
  ---  -----
  1     Greg
  2     Alan 
  3    George 
  4     John 
  5     Peter   

第二张桌子

 id       aid        data   
 ---     -----      -------
 1        2          CCCV   
 2        2          VVVV 
 3        3          DDDDD 
 4        3          SSSS 
 5        4          PPPPP 

我希望加入的结果是:

 id(1st table)  aid   name    Data   Number
 -----------    ----  -----   -----  -----
 1               null  Greg    null   1
 2                1    Alan    CCCV   1
 2                2    Alan    VVVV   2
 3                3    George  DDDDD  1
 3                4    George  SSSS   2
 4                5    John    PPPPP  1
 5               null  Peter   null   1

我搜索了很多,我找不到任何东西。也许我不知道如何搜索,或者没有我想做的事情。

4

3 回答 3

2

根据我的评论,您已经标记了 MySQL 和 PostgreSQL。

这个答案适用于 PostgreSQL。

SELECT
  table1.id,
  table2.aid,
  table1.name,
  table2.data,
  ROW_NUMBER() OVER (PARTITION BY table1.id ORDER BY table2.aid) AS number
FROM
  table1
LEFT JOIN
  table2
    ON table1.id = table2.aid
于 2012-10-22T10:54:09.563 回答
2
SELECT Table1.id, Table2.id as aid, Table1.name, Table2.data,
GREATEST(1, (SELECT COUNT(*)
             FROM Table2 t2
             WHERE t2.aid = Table1.id
             AND t2.id <= Table2.id))
AS number
FROM Table1
LEFT JOIN Table2
ON Table2.aid = Table1.id
ORDER BY id, aid;

适用于 MySQL 和 PostgreSQL。

于 2012-10-22T12:10:28.637 回答
0

查询没有窗口函数的 PostgreSQL 8.3。
对于更大的表JOIN,使用 a而不是相关的子查询通常要快得多。
第一个查询在加入 toTable2 之前Table1聚合值,这也应该更快:

SELECT t1.id, t2.aid, t1.name, t2.data, COALESCE(t2.ct, 1) AS number
FROM   Table1 t1
LEFT   JOIN  (
    SELECT x.aid, x.data, count(y.aid) + 1 AS ct
    FROM   Table2 x
    LEFT   JOIN Table2 y ON x.aid = y.aid AND x.id > y.id
    GROUP  BY x.aid, x.data
    ) t2 ON t2.aid = t1.id
ORDER  BY t1.id, t2.ct;

并且ORDER BY应该修复。

没有子查询的替代方案。可能会更快,但是:

SELECT t1.id, t2.aid, t1.name, t2.data, count(*) + count(t3.id) AS number
FROM   Table1 t1
LEFT   JOIN Table2 t2 ON t2.aid = t1.id
LEFT   JOIN Table2 t3 ON t3.aid = t2.aid AND t3.id < t2.id
GROUP  BY t1.id, t2.aid, t1.name, t2.data
ORDER  BY t1.id, count(t3.id);

不确定,没有用更大的集合进行测试。用 测试性能EXPLAIN ANALYZE。你能报告你的结果吗?

于 2012-10-22T19:29:51.917 回答