mysql显示子查询中的字段值

标签 mysql subquery field

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

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/

相关文章:

mysql - 将连接查询转换为子查询

php - mysql - 如何将主查询值传递到子查询中的连接

PHP - 严格的标准 : Only variables should be passed by reference

java.sql.SQLException : No suitable driver found for jdbc:mysql://localhost:3306 异常

mysql : ORDER BY Twice

c# - 检查通用类型的字段

java - 如何让方法使用java中子类的字段?

c# - 在c#中向数据表添加行

python - "incorrect string value"但可以用 UTF-8 解码

Java-反射 : Get fields belonging to current class only