Cross Join Combination Matrix

Build a full combination matrix with CROSS JOIN, then LEFT JOIN real facts onto the skeleton so empty combinations show as zero instead of disappearing.

SqlData Fetching

Code

snippet
-- 笛卡尔积:每个尺寸 × 每种颜色 = 全组合,库存矩阵的行骨架
CREATE TABLE sizes  (size_id text PRIMARY KEY);
CREATE TABLE colors (color_id text PRIMARY KEY);
CREATE TABLE stock (
    size_id  text,
    color_id text,
    stock    integer NOT NULL DEFAULT 0
);

INSERT INTO sizes  VALUES ('S'), ('M'), ('L');
INSERT INTO colors VALUES ('black'), ('white');

SELECT
    s.size_id,
    c.color_id,
    s.size_id || '-' || c.color_id AS sku_hint
FROM sizes s
CROSS JOIN colors c
ORDER BY s.size_id, c.color_id;

-- 组合矩阵再 LEFT JOIN 真实库存:缺货组合显式显示为 0,而不是消失
SELECT
    s.size_id,
    c.color_id,
    COALESCE(st.stock, 0) AS stock
FROM sizes s
CROSS JOIN colors c
LEFT JOIN stock st
    ON st.size_id = s.size_id AND st.color_id = c.color_id
ORDER BY s.size_id, c.color_id;

Inside the snippet

Several statements share this file — SELECT / INSERT / CREATE, with sizes, colors and stock among the objects involved.

In terms of clauses, the statements use: 3 JOINs combining rows across tables; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.

Points of care

  • 3 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.

Putting it to use

The sizes table is the working surface here.

Core lines

SELECT
s.size_id,
c.color_id,
COALESCE(st.stock, 0) AS stock
FROM sizes s
CROSS JOIN colors c
LEFT JOIN stock st
ON st.size_id = s.size_id AND st.color_id = c.color_id
ORDER BY s.size_id, c.color_id;
SELECT
s.size_id,
c.color_id,
s.size_id || '-' || c.color_id AS sku_hint
FROM sizes s
CROSS JOIN colors c
ORDER BY s.size_id, c.color_id;
CREATE TABLE stock (
size_id  text,
color_id text,
stock    integer NOT NULL DEFAULT 0
);

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`sizes`, `colors`, `stock`, combined through 3 joins.