我有两个表(X 和 Y),其中包含“电子邮件”列(列名称:表 x 中的 EmailX 和表 y 中的 EMailY)。我想在表 X 中添加一列,当表 X 中的电子邮件地址是表 Y 中的电子邮件地址之一时,该列填充"is";当表 X 中的电子邮件地址不是电子邮件地址之一时,该列填充“否”在表Y中。
我该怎么做?
感谢您的支持!
最佳答案
不要在数据库中冗余存储数据。由于您始终可以检查表 y 中是否存在条目,因此不应向表 x 添加标志来指示这一点。
以下是如何通过 EXISTS
获取信息:
select
x.*,
case when exists (select * from y where y.emaily = x.emailx) then 'yes' else 'no' end
as exists_in_y
from x;
与 IN
相同我更喜欢简单一点:
select
x.*,
case when emailx in (select emaily from y) then 'yes' else 'no' end as exists_in_y
from x;
与外连接相同
select
x.*,
case when emaily is not null then 'yes' else 'no' end as exists_in_y
from x
left join (select distinct emaily from y) y on y.emaily = x.emailx;
如果 emaily 在 y 中已经是唯一的,您可以直接从表中选择(改为 left join y on y.emaily = x.emailx
。
这是个人选择的问题。我选择IN
通常,使用 EXISTS
条件为<
和>
,当我想要另一个表中的多个字段时,请使用联接。
关于mysql - 使用 MYSQL 根据另一个表中的现有条目添加条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41266733/