MySQL:多表 - 一对多关系,获取子列之一不为空的列

标签 mysql sql

我在创建 sql 查询方面需要帮助。

我想获取所有 child 的 res_id 都不为 null 的订单。

在下面的示例中,您将看到 order_audit.order_id W1 有一个 许多关系 temp_order_id W1_1W1_2。此 temp_order_id 还有 res_id 1232。此命令 W1 应作为响应。

W2 的情况下,您可以看到 W2_1 具有 resp_id null。所以这个不应该拉。

order_audit

+----+----------+
| id | order_id |
+----+----------+
|  1 | W1       |
|  2 | W2       |
|  2 | W3       |
+----+----------+

order_mapping

+----------+---------------+
| order_id | temp_order_id |
+----------+---------------+
| W1       | W1_1          |
| W1       | W1_2          |
| W2       | W2_1          |
| W2       | W2_2          |
| W3       | W3_1          |
+----------+---------------+

temp_order_table

+---------------+--------+
| temp_order_id | res_id |
+---------------+--------+
| W1_1          | 12     |
| W1_2          | 32     |
| W2_1          | null   |
| W2_2          | 33     |
| W3_1          | null   |
+---------------+--------+

从您的屏幕截图看来,Account 中有一个前导空格(也许还有尾随空格)。

任何形式的帮助将不胜感激

最佳答案

您可以自然地连接所有其他 2 个表并检查 res_id 是否为空。

select oa.id, oa.order_id from order_audit oa
  where not exists (
    select * from order_mapping om
    join temp_order_table tot on
    tot.temp_order_id = om.temp_order_id
    where om.order_id = oa.order_id and tot.res_id is null
  )

这是 sqlfiddle 的链接 link

关于MySQL:多表 - 一对多关系,获取子列之一不为空的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52015253/

相关文章:

sql - PostgreSQL:将列提取到单独的表中并使用相关键更新其他列

mysql - COUNT (DISTINCT) 有条件

php - MySQL 连接 ('max_user_connections' )

sql - 在SQL Server 2005中,如何设置整数列以确保值大于0?

sql - VB.Net SQLExpress 2008 部署

java - jdbc 中的未知数据库

php - 从magento安装中的php文件运行自定义sql

mysql - 多少查询太多了?

php - 表结构

mysql - 从数据中获取第一个记录的发生日期