【问题标题】:How to select all from table one based on a value, then select from same table with value from that table?如何根据一个值从一个表中选择所有值,然后从同一个表中选择该表中的值?
【发布时间】:2020-04-25 10:54:25
【问题描述】:

我有一个用户表,看起来像这样。 Socialnr 在一行或多行中为空。

Userid:1 Phone:12345 Email:test@test.com Socialnr:88776655
Userid:2 Phone:12345 Email:              Socialnr:
Userid:3 Phone:      Email:test@test.com Socialnr:

假设我从一开始就只有 Socialnr。 所以从这里我需要

select * from users where socialnr=88776655

但是我还需要能够根据从第一次选择中获得的相同电子邮件或电话号码来选择另外两行。 我需要单独的行。 任何意见表示赞赏,谢谢。

根据 Gordons 的回答,我现在用我的真实代码得到了这个。

SELECT u.* FROM appmanager.appusers u where u.userId='797' and u.personnrvh2='88776655' OR exists (select 1 from appmanager.appusers u2 where u2.userId='797' and u2.personnrvh2='88776655'  and (u2.emailvh2 = u.emailvh2 or u2.mobilvh2 = u.mobilvh2))

好的,这就是解决方案,非常感谢 Gordon!

【问题讨论】:

  • 请用您正在使用的数据库标记您的问题:oracle、sql-server、postgresql...?

标签: mysql sql asp-classic


【解决方案1】:

嗯。 . .根据您的描述,您可以使用exists

select u.*
from users u
where u.Socialnr = 88776655 or
      exists (select 1
              from users u2
              where u2.Socialnr = 88776655 and
                    (u2.email = u.email or u2.phone = u.phone)
             );

如果你愿意,你也可以使用窗口函数。 . .假设每个emailphone 都有一个终极Socialnr

select u.*
from (select u.*,
             max(Socialnr) over (partition by email) as imputed_socialnr_email,
             max(Socialnr) over (partition by phone) as imputed_socialnr_phone
      from users u
     ) u
where 88776655 in (Socialnr, imputed_socialnr_email, imputed_socialnr_phone)

【讨论】:

  • 谢谢 Gordon,我想你的第一个解决方案就快到了。我得到了正确的行,但它也显示了具有不同用户 ID 的行,而不仅仅是我应该的用户 ID 797。我将用我现在拥有的真实代码更新我的问题。
  • 谢谢 Gordon,第一个解决方案就是这个。太好了!
  • @ClaesGustavsson 。 . .我既不理解对您的问题的反对意见,也不理解对我的回答的反对意见。
  • 不,我也没有,但我很高兴你帮助了我 :-) 再次感谢!
  • 我认为您需要添加一个例外,例如AND NOT u.email = '',这样如果一行包含社交号码但没有电子邮件,它就不会检查空列值。否则它将列出所有没有电子邮件的行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
  • 2014-12-16
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 2012-03-04
相关资源
最近更新 更多