我有以下關系。一個package有多個versions。
CREATE TABLE IF NOT EXISTS package (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL UNIQUECREATE TABLE IF NOT EXISTS version (
id SERIAL PRIMARY KEY,
package_id INT NOT NULL REFERENCES 包。
version TEXT NOT NULL。
UNIQUE(package_id, version)
);
一個版本有多個依賴項。這些依賴關系又是其他軟體包的版本。
CREATE TABLE IF NOT EXISTS dependency (
version_id INT NOT NULL REFERENCES version,
dependency_id INT NOT NULL REFERENCES version
);
以JavaScript/Node.js生態系統中的npm注冊表為例。你可以使用下面的命令生成一個依賴樹。
npm list --prod
這就列出了所有的生產依賴項。
├── [email protected]
│ ├── @babel/[email protected] deduped
│ ├── history@4.10.1
│ ├── @babel/[email protected] deduped
│ │ ├── [email protected] deduped
│ │ ├── [email protected]
│ │ ├── [email protected] deduped
│ │ ├── [email protected] deduped
│ │ └──[email protected]
│ ├──[email protected] 洗掉
│ ├──[email protected]
│ │ ├──[email protected] 刪減了
│ │ └── [email protected] deduped
│ │ └──[email protected]
│ ├──[email protected]
│ │ ├── @babel/[email protected] deduped
│ ├── history@4.10.1 deduped
│ │ ├── [email protected] deduped
│ │ ├── [email protected] deduped
│ │ ├──[email protected]
│ │ ├── @babel/[email protected] deduped
│ │ ├── [email protected] deduped
│ │ ├── [email protected] deduped
│ │ └── [email protected] deduped
│ │ ├──[email protected]
│ │ └──[email protected]
│ │ ├── [email protected] deduped
│ │ ├──[email protected]
│ │ ├── [email protected] 刪減版
│ ├──[email protected] 刪減。
│ │ └── [email protected] deduped
│ ├──[email protected] 刪減。
│ ├──[email protected]
│ └──[email protected]
正如你在例子中看到的,[email protected]依賴于[email protected],而后者依賴于[email protected]。
我們的想法是在一個資料庫中擁有所有的包和它們的版本,并找到一個查詢,列出某個包的所有依賴關系。我想找到一個能(或多或少)給我以下結果的查詢。
| name | version | level |
--------------------------------------
| react-router-dom | 5。 2.0 | 1 |
| @babel/runtime | 7。 13.17 | 2 |
| 歷史 | 4.10。 1 | 2 |。
| @babel/runtime | 7。 13.17 | 3 |
| loose-envify| 1. 4.0 | 3 |
| resolve-pathname | 3。 0.0 | 3 |
| ...
| prop-types | 15。 7.2 | 2 |
| ... | ... | ... | ...
我創建了一個小的sql fiddle,其中有一些假資料,可以作為一個游樂場 - http://sqlfiddle.com/#!17/633dd。
我認為遞回公共表運算式是一種方式,但我有點迷茫,因為我還沒有使用它們。我發現了一個典型的例子,人們都有經理,你可以生成組織結構圖,但我沒能把它轉移到我的問題上。
WITH RECURSIVE cte_name AS (
CTE_query_definition --非遞回術語 UNION [ALL]
CTE_query定義--遞回術語。
) SELECT * FROM cte_name。
非常感謝您的幫助!
uj5u.com熱心網友回復:
下面是一個cte,它產生了一個包(在這種情況下,包的version_id為1)的所有依賴性:
with recursive cte(v_id, d_id, l) as (
select d.*, 1 from dependency dwhere d. version_id = 1
union all
select case when d. version_id is null then c.d_id else d.version_id end,
case when d. dependency_id is null then null else d. dependency_id end。
c.l 1.
from cte c left join dependency d on c。 d_id = d.version_id where c.d_id is not nullselect v.package_id, p.name, v.version, c.l
from cte c join version v on v.id = c。 v_id join package p on p.id = v.package_id
group by v.package_id, p.name, v.version, c.l
order by v.package_id。
查看演示此處.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/319320.html
標籤:
