[英]MySQL join table based on condition
我有一个要求,如果某些条件匹配,那么我需要应用 JOIN 否则,我不需要应用它。
例如
A、B 和 C 是表格
所以我需要加入 B 和 C 如果 B.id 不在(从 A 中选择 entityId),否则将没有加入。
同样在这里 A 和 C 没有共同的值。
Table A
id entityId name
1 xyz abc
2 bcd z
3 edc x
Table B
id entityId shopRegID
1 bcd z
Table C
id entityId newEntityID ShopNewname
1 xyz xyze abcd
2 e ee sd
现在我有这样的条件,我需要根据提供给我的 entityId 从这些表中获取数据。 我需要删除所有未注册的商店(不在表 B 中)但包括重命名的商店(在表 C 中但不在 B 中)
假设如果给定 ('xyz','bcd','edc') output 应该包含 bcd (因为它在表 B 中) xyz (因为它在表 C 中)
这些表有非常大量的数据(10万)
实现这一目标的最佳和高效方法是什么。
您可以按如下方式使用left join
和coalesce
:
select *
from tableA A
left join tableB B on a.entityid = b.entityid
left join tableB C on a.entityid = c.entityid
WHERE coalesce(b.entityid,c.entityid) is not null
听起来您想要来自任a
表中的实体。 这表明exists
逻辑:
select a.*
from a
where exists (select 1 from b where b.entityId = a.entityId) or
exists (select 1 from c where c.entityId = a.entityId)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.