PostgreSQL - With 语句有一个 table 来自许多不同的
PostgreSQL - With statement to have one table from many different
我有 4 个这样的 table
table a:
art_id | name | surname
-------+-------+--------
1 | John | McA
2 | Alex | McB
3 | Juddy | McC
table b:
art_id is a foreign key to table a
diff_id is foreign key to table c
art_id | title | diff_id
-------+-------+--------
1 | smth | 1.1
2 | else | 1.2
3 | here | 1.3
table c:
class is foreign key to table d
class | date | diff_id
-------+-------+--------
a | 01.02 | 1.1
b | 02.03 | 1.2
c | 03.04 | 1.3
table d:
class | deputy|
-------+-------+
a | John |
b | Marc |
c | Sophie|
我正在尝试编写一个 postresql 语句来使 table 如:
table result:
| title | deputy |
+-------+--------+
| smth | John |
| else | Marc |
| here | Sophie |
我正在尝试通过 WITH AS 语句 bun 来做到这一点,但我被卡住了。
在语句中创建递归 table 之后,我试图通过执行 LEFT JOIN 语句来解决该问题,但它乘以结果 table.
中的记录
感谢您的帮助!
我认为您使用递归查询和存储即时值使您的任务过于复杂。我相信简单的 JOIN
就足以满足您要实现的目标。
SELECT
b.title, d.deputy
FROM
b
INNER JOIN c ON b.diff_id = c.diff_id
INNER JOIN d ON c.class = d.class
如果您需要在代理列中没有匹配值时显示标题,那么您可能需要将 INNER
更改为 LEFT
连接类型。
此外,如果您收到一个 title
的多个结果且 deputy
列中的值完全相同,请考虑添加 DISTINCT
子句:
SELECT DISTINCT
b.title, d.deputy
FROM
b
INNER JOIN c ON b.diff_id = c.diff_id
INNER JOIN d ON c.class = d.class
如果您真的觉得有必要包含 table a
然后重写查询:
SELECT
b.title, d.deputy
FROM
a
INNER JOIN b ON a.art_id = b.art_id
INNER JOIN c ON b.diff_id = c.diff_id
INNER JOIN d ON c.class = d.class
我有 4 个这样的 table
table a:
art_id | name | surname
-------+-------+--------
1 | John | McA
2 | Alex | McB
3 | Juddy | McC
table b:
art_id is a foreign key to table a
diff_id is foreign key to table c
art_id | title | diff_id
-------+-------+--------
1 | smth | 1.1
2 | else | 1.2
3 | here | 1.3
table c:
class is foreign key to table d
class | date | diff_id
-------+-------+--------
a | 01.02 | 1.1
b | 02.03 | 1.2
c | 03.04 | 1.3
table d:
class | deputy|
-------+-------+
a | John |
b | Marc |
c | Sophie|
我正在尝试编写一个 postresql 语句来使 table 如:
table result:
| title | deputy |
+-------+--------+
| smth | John |
| else | Marc |
| here | Sophie |
我正在尝试通过 WITH AS 语句 bun 来做到这一点,但我被卡住了。 在语句中创建递归 table 之后,我试图通过执行 LEFT JOIN 语句来解决该问题,但它乘以结果 table.
中的记录感谢您的帮助!
我认为您使用递归查询和存储即时值使您的任务过于复杂。我相信简单的 JOIN
就足以满足您要实现的目标。
SELECT
b.title, d.deputy
FROM
b
INNER JOIN c ON b.diff_id = c.diff_id
INNER JOIN d ON c.class = d.class
如果您需要在代理列中没有匹配值时显示标题,那么您可能需要将 INNER
更改为 LEFT
连接类型。
此外,如果您收到一个 title
的多个结果且 deputy
列中的值完全相同,请考虑添加 DISTINCT
子句:
SELECT DISTINCT
b.title, d.deputy
FROM
b
INNER JOIN c ON b.diff_id = c.diff_id
INNER JOIN d ON c.class = d.class
如果您真的觉得有必要包含 table a
然后重写查询:
SELECT
b.title, d.deputy
FROM
a
INNER JOIN b ON a.art_id = b.art_id
INNER JOIN c ON b.diff_id = c.diff_id
INNER JOIN d ON c.class = d.class