使用 Table 1 作为标题列,使用 Table 2 作为内容列

Using Table 1 as Title column and Table 2 as Content columns

我有两个表:

Table 1: 类别 Table

CatCode CatDesc Total
CAT0001 Drinks 22
CAT0002 Food 12

Table 2:产品Table

ProdCode ProdDesc Amount CatCode
P00001 Coke 10 CAT0001
P00002 Pepsi 12 CAT0001
P00003 Burger 5 CAT0002
P00004 Fries 5 CAT0002
P00005 Eggs 2 CAT0002

我想问一下是否可以得到 sql 结果,其中 Table 1 包含类别代码、类别描述和总计,但在下一列中包含 Table 2 其中包含产品代码、产品名称和数量?

预期结果:

CAT0001 Drinks 22
P00001 Coke 10
P00002 Pepsi 12
CAT0002 Food 12
P00003 Burger 5
P00004 Fries 5
P00005 Eggs 2
  1. 试试这个(在 dbfiddle 上测试过)
SELECT catcode as code, catdesc as name, total as amount
FROM (
  SELECT catcode, catdesc, total, catcode AS catcode2 FROM category
  UNION ALL
  SELECT prodcode, proddesc, amount, catcode AS catcode2 FROM product
) tmp
ORDER BY catcode2, catcode;