mysql子查询字段不存在,但查询全部

mysql子查询字段不存在,但查询全部,mysql,subquery,Mysql,Subquery,oh_mr_base_info不包含字段mr_id; 但是返回所有oh\u mr\u ocr\u sub\u info数据?为什么?这就是SQL的工作方式:) 如果给表指定别名,您将看到查询将不再工作 mysql> select id,mr_id,type from oh_mr_ocr_sub_info where mr_id in (select mr_id from oh_mr_base_info) limit 2; +----+-------+--------------+ |

oh_mr_base_info
不包含字段
mr_id
; 但是返回所有
oh\u mr\u ocr\u sub\u info
数据?为什么?

这就是SQL的工作方式:)

如果给表指定别名,您将看到查询将不再工作

mysql> select id,mr_id,type from oh_mr_ocr_sub_info where mr_id in

 (select mr_id from oh_mr_base_info) limit 2;

+----+-------+--------------+
| id | mr_id | type         |
+----+-------+--------------+
|  2 |     7 | inhospital   |
|  3 |     7 | chemotherapy |
+----+-------+--------------+

2 rows in set (0.01 sec)

mysql> select mr_id from oh_mr_base_info;

ERROR 1054 (42S22): Unknown column 'mr_id' in 'field list'
上面会给出一个错误,即b1.mr_id是无效列。然而,如果你写a1.mr_id,它将毫无问题地工作

这并不完全是关于表别名,而是关于表列。它看到mr_id不需要存在于B1中,它也可以存在于a1中。这与选择一个常量相同

select a1.id,
       a1.mr_id,
       a1.type 
  from oh_mr_ocr_sub_info a1
 where a1.mr_id in (select b1.mr_id 
                   from oh_mr_base_info b1)
 limit 2;

只要oh_mr_base_info中有任意数量的可用记录,查询将返回111。对于这类问题,最好使用表别名

谢谢,这可以解决我的问题,但为什么?是否有关于mysql子查询执行过程的任何活动?这是一个“相关子查询”。
WHERE
子句中的子查询可以引用外部查询中的列。这样做通常是为了允许将子查询中的行与主查询中的当前行进行比较,但它也适用于
SELECT
列表。这是关于子查询优化的,它变成了EXISTS
select 111 from oh_mr_base_info;