gpt4 book ai didi

mysql - 选择列值为 NEVER x 的行

转载 作者:行者123 更新时间:2023-11-29 05:51:16 24 4
gpt4 key购买 nike

我有一个链接到另一个表的表。一张表包含运营商,另一张表包含运营商的routes。路由表有一个 carrier_id 列和一个 status 字段,它确定路由的事件状态,0 是事件状态.

我试图列出没有有效路线的承运人,这让我处于不稳定的境地,在这种情况下,很容易选择根本没有路线的承运人,但查询的第二方给我带来了麻烦。

SELECT c.id
, c.title
FROM carriers c
LEFT
JOIN routes r
ON r.carrier_id = c.id
WHERE r.route_id IS NULL
OR (r.status > 0 AND r.carrier_id = c.id)

这个问题相当明显 - 结果表得到误报 - 具有存档和未存档路线的承运人。我很确定 SQL 采用了某种构造,我可以用它来指定如下内容:

if any of carrier.routes.status == 0 exclude carrier from selection

这几乎就是问题的归结。

更新:有人要求我提供数据集和该数据集的预期结果,因此我在下面提供:

运营商:

--------------
| id | title |
--------------
| 1 | foo |
| 2 | bar |
| 3 | baz |
--------------

路线:

----------------------------
| id | carrier_id | status |
----------------------------
| 1 | 1 | 0 |
| 2 | 1 | 1 |
| 3 | 2 | 1 |
----------------------------

使用以下数据,应该返回承运人 2 和 3,因为 3 没有事件路线,而且 2 也没有。但是,1 有事件路线,因此被排除在这次选择之外。

最佳答案

这样试试

SELECT carrier.id, carrier.title
FROM carriers LEFT JOIN routes
ON routes.carrier_id = carrier.id and
(route.route_id IS NULL OR (route.status > 0)

请注意 Where (route.route_id IS NULL OR (route.status > 0) 子句将您的左连接隐式转换为内连接

更好更清洁的解决方案

Select * from carriers
Where exists
(
Select 1 from routes where routes.carrier_id = carrier.id and status != 0
) or carriers.route_id is null.

OP 的注释:我实际发现对我有用的是基于上面的逻辑,并且是这样的:

Select * from carriers
Where exists
(
Select 1 from routes where routes.carrier_id = carrier.id and status != 0
) and not exists
(
Select 1 from routes where routes.carrier_id = carrier.id and status != 0
) or carriers.route_id is null.

关于mysql - 选择列值为 NEVER x 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53915537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com