MySql列出直接和间接子记录

时间:2018-11-06 09:33:16

标签: mysql sql

我有一个用于处理运输项目的3表数据库模式。运输工具可以包含多个盒子和多个物品。除此之外,一个盒子还可以包含多个项目。因此,可以直接或间接将物品附加到运输工具上。

简化的DDL是这样的:

CREATE TABLE transport (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `transport_number` varchar(50) NOT NULL,
  `transport_date` datetime NOT NULL
)

CREATE TABLE box (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) NOT NULL,
  `transport_id` int(11) NOT NULL
)

CREATE TABLE item (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) DEFAULT NULL,
  `box_id` int(11) DEFAULT NULL,
  `transport_id` int(11) DEFAULT NULL
)

我尝试实现一个查询,该查询选择带有包装箱和物品计数的所有运输工具。像这样:

预期结果:

TRANSPORT_ID | TRANSPORT_NUMBER | BOX_COUNT | ITEM_COUNT
--------------------------------------------------------
1            | T1               | 2         | 3
2            | T2               | 1         | 2

样本数据

运输:

ID     | TRANSPORT_NUMBER | TRANSPORT_DATE
------------------------------------------
1      | T1               | 2018-11-06
2      | T2               | 2018-11-06

方框:

ID     | TITLE            | TRANSPORT_ID
------------------------------------------
1      | B-1              | 1
2      | B-2              | 1
3      | B-3              | 2

项目:

ID     | TITLE            | BOX_ID    | TRANSPORT_ID
----------------------------------------------------
1      | I-1              | 1         | NULL
2      | I-2              | 2         | NULL
3      | I-3              | NULL      | 1
4      | I-4              | 3         | NULL
5      | I-5              | 3         | NULL

2 个答案:

答案 0 :(得分:1)

一个想法是实现所有可用的关系,然后相应地对它们进行总计:

SELECT 
t.id, 
t.transport_number, 
COUNT(distinct b.id) as box_count, 
COUNT(distinct i.id) + COUNT(distinct i2.id) as item_count
FROM transport t
LEFT JOIN box b ON t.id = b.transport_id
LEFT JOIN item i ON b.id = i.box_id
LEFT JOIN item i2 ON t.id = i2.transport_id
GROUP BY t.id

答案 1 :(得分:0)

如果性能不成问题,这应该可以工作:

SELECT 
  transport.id,
  transport.transport_number,
  (SELECT COUNT(*) FROM box WHERE box.transport_id = transport.id) AS box_count,
  (SELECT COUNT(*) FROM item WHERE item.transport_id = transport.id OR item.box_id IN (SELECT id FROM box WHERE box.transport_id = transport.id)) AS item_count
FROM transport;