我有以下可以正常工作的查询:
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。
我该如何完成这个任务?
谢谢您并致以诚挚的问候
最佳答案
如果您想要来自多个表的结果,您应该将这些表连接在一起。 由于您只需要 A 中存在于 B 中的记录,因此需要使用外部 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.
关于mysql显示子查询中的字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32098947/