作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个名为 imported_cables_entry
和 imported_cables_entry
的子表,以及一个名为 cables_entry
的父表。这两个子项具有名为 cables_id
的外键列,指向 cables_entry
的主键 id
。
我想要实现的是,编写一个查询,该查询从父级中检索符合以下条件的所有数据:
如果imported_cables_entry
.cables_id
= cables_entry
.id
如果 local_cables_entry
.cables_id
= cables_entry
.id
这两个条件都可以正常工作,但检索到 0 个结果。当它们一一执行时,我就会得到正确的结果。
Retrieve all the data from parent table, where the conditions for child tables meets. When the Unique
id
of the parent and thecables_id
of the children matches with either conditions.
查询
SELECT `cables_entry`.*, `imported_cables_entry`.*, `local_cables_entry`.*
FROM `cables_entry`
JOIN `imported_cables_entry`
ON `imported_cables_entry`.`cables_id` = `cables_entry`.`id`
JOIN `local_cables_entry`
ON `local_cables_entry`.`cables_id` = `cables_entry`.`id`
最佳答案
假设子表的列相同,您可以编写以下查询:
SELECT
ce.*,
COALESCE(ice.column1, lce.column1) AS column1,
COALESCE(ice.column2, lce.column2) AS column2
FROM cables_entry ce
LEFT JOIN imported_cables_entry ice ON ice.cables_id = ce.id
LEFT JOIN local_cables_entry lce ON lce.cables_id = ce.id
如果cables_entry中可能有一个不在ice或lce中的条目,并且您不想显示它们,则可以添加一个WHERE子句:
WHERE ice.id IS NOT NULL OR lce.id IS NOT NULL
编辑:如果您的子表完全不同,并且您不介意有多个空列值,则可以简单地使用以下查询:
SELECT
ce.*,
ice.*,
lce.*
FROM cables_entry ce
LEFT JOIN imported_cables_entry ice ON ice.cables_id = ce.id
LEFT JOIN local_cables_entry lce ON lce.cables_id = ce.id
关于mysql - 连接单父表的两个子表以检索数据 - MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58975776/
我是一名优秀的程序员,十分优秀!