mysql 显示来自子查询的字段值

mysql display field values from subquery

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

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 .

如何完成此操作?

谢谢你和最好的问候

如果您想要来自多个表的结果,您应该将这些表连接在一起。 由于您只想要 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.