gpt4 book ai didi

mysql - 连接单父表的两个子表以检索数据 - MySQL

转载 作者:行者123 更新时间:2023-11-29 09:29:40 25 4
gpt4 key购买 nike

我有两个名为 imported_cables_entryimported_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 the cables_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/

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