【问题标题】:mysql display field values from subquerymysql 显示来自子查询的字段值
【发布时间】:2015-08-19 14:53:33
【问题描述】:

我有以下正常工作的查询:

select * from myTable a where a.company is null and exists (select b.company from myTable b where b.id = a.id and b.office_id = a.office_id and b.company is not null);

现在,我还想在 myTable a 的字段旁边显示子查询中的字段值 b.company

我该如何完成这项工作?

谢谢你和最好的问候

【问题讨论】:

  • 使用外连接代替存在检查

标签: mysql subquery field


【解决方案1】:

如果您想要来自多个表的结果,您应该将这些表连接在一起。 由于您只需要 B 中存在的来自 A 的记录,因此您需要使用外部 JOIN 来返回来自 A 的所有记录以及仅在 B 中匹配的记录。但是您想要排除 A 中未在 B 中找到的所有记录。

SELECT *, b.company
FROM  myTable a 
LEFT JOIN myTable B 
  ON b.id = a.id 
 and b.office_id = a.office_id
 and b.company_ID is not null
WHERE a.company is null 
  and B.ID is not null and B.office_ID is not null --this handles the exists part.

【讨论】:

  • 哇,我有几次加入失败了......现在应该是正确的。
  • 好的,这很好用。但是如何通过使用 sql 而不循环通过结果集来将 a.company 更新为 b.company 的值?谢谢。
  • 查看整个网站的示例:这里有一个 stackoverflow.com/questions/15209414/mysql-update-joinstackoverflow.com/questions/806882/… 如果您正在努力实现上述内容,请提出一个不同的问题,我很肯定您会得到帮助.我们尝试保持每个问题独立于其他问题,以便每个问题/答案对都满足特定需求。通过在此处进行跟进,它会使问题复杂化,并使其对其他人的价值降低。
猜你喜欢
  • 1970-01-01
  • 2021-02-22
  • 2016-08-17
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多