# sql查询子表状态全部完成的数据

* 抖音：<https://v.douyin.com/hckuLef/>
* B站：<https://www.bilibili.com/video/BV1c34y1R7E6/>

这种需求你们都是怎么写sql的

举例来说有个订单表里面有5个订单

然后还有一个运单表

每个订单下可能有不同数量的运单

运单有一个状态是0和1

0代表未完成

一代表已完成

现在需求是把订单2和订单4查出来

因为他们下面

所有的运单都已经完成了

我们来看一下

好这个是单独查订单表有5条数据

那我们把运单也关联进来

我们用 left join

好然后我们也不需要这么多参数

只看

订单 id 和

运单状态

大家看：这数据就多了

一共12条数据

跟这个是一样的

那接下来呢

我们要想办法把订单2和订单4

查出来首先我们加一个分组

跟 rope by 我们按照订单 id 分组

也就是说同一个订单的运单放在一组

然后呢我们来看一下他们的数量

cut 星

接下来呢我们要想办法把

第二个订单和第四个订单找出来

那怎么找呢

我们可以利用他的这个状态值

让我们来看一下前三个订单（口误：运单）

大家看他们的 status 相加总和

他就是一

那第二个订单（的4个运单）呢

他们的 status 相加总和是4

正好跟他的数量是一样的

我们来看一下

sum bt.status

这里边只有2号和4号

他们的数量和他们的sum正好相等

所以呢我们可以用having

count \*

等于 sum

bt.status

好我们再来看一下

大家看：只查出了2号和4号两个订单

也就是说：我们按照订单分组

然后取他们运单状态的总和

如果等于他们运单的数量

那我们就把这条数据筛出来

所以这块，如果我们还需要其他参数

比如：订单编号

我们可以把这些参数加进来

订单地址

那我们也可以在这查出来

好这样就可以了


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sunzsh.gitbook.io/xiaoshan.bug/sql-cha-xun-zi-biao-zhuang-tai-quan-bu-wan-cheng-de-shu-ju.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
