Market Basket Item Pairs
A self-join with a.item < b.item counts unordered item pairs per order, and ORDER BY the pair frequency surfaces the baskets that sell together.
Code
-- 购物篮 (market basket) 分析:订单内商品两两配对 (pairs) 计数
CREATE TABLE order_items (
order_id int NOT NULL,
item text NOT NULL
);
INSERT INTO order_items VALUES
(1, 'coffee'), (1, 'milk'), (1, 'sugar'),
(2, 'coffee'), (2, 'milk'),
(3, 'tea'), (3, 'sugar'),
(4, 'coffee'), (4, 'sugar');
-- a.item < b.item 同时消除 (A,B)/(B,A) 重复与自配对
SELECT a.item AS item_a,
b.item AS item_b,
COUNT(*) AS orders_together
FROM order_items a
JOIN order_items b
ON a.order_id = b.order_id AND a.item < b.item
GROUP BY a.item, b.item
ORDER BY orders_together DESC, item_a, item_b
LIMIT 3;
DROP TABLE order_items;The way it runs
SELECT / INSERT / CREATE statements share the script, touching order_items.
What the statements actually assemble: one JOIN combining rows across tables; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; NOT NULL qualifiers on the required columns.
Applying it
Run the statement against the order_items table; the LIMIT keeps the probe cheap while you tune the predicates.
Statements that matter
SELECT a.item AS item_a,
b.item AS item_b,
COUNT(*) AS orders_together
FROM order_items a
JOIN order_items b
ON a.order_id = b.order_id AND a.item < b.item
GROUP BY a.item, b.item
ORDER BY orders_together DESC, item_a, item_b
LIMIT 3;
INSERT INTO order_items VALUES
(1, 'coffee'), (1, 'milk'), (1, 'sugar'),
(2, 'coffee'), (2, 'milk'),
(3, 'tea'), (3, 'sugar'),
(4, 'coffee'), (4, 'sugar');
CREATE TABLE order_items (
order_id int NOT NULL,
item text NOT NULL
);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables or CTEs does it reference?
- `order_items` — joined via one JOIN clause.
Report a problem with this exampleOpens a pre-filled issue on GitHub.