我想在my_table上使用查询中的id来从my_table_2中选择所有field_b行。
SELECT field_b
FROM my_table_2
WHERE my_id_2 IN (
SELECT my_id FROM my_table WHERE field_a = 1234
);
我让ERROR 1054 (42S22): Unknown column 'my_id_2' in 'IN/ALL/ANY subquery'
执行上述查询。
以下是我的表格示例供参考:
mysql> select * from my_table;
+-------+---------+
| my_id | field_a |
+-------+---------+
| 1 | 1234 |
+-------+---------+
| 2 | 1234 |
+-------+---------+
2 row in set (0.00 sec)
mysql> select * from my_table_2;
+-------+-----------+
| my_id_2 | field_b |
+---------+---------+
| 1 | 5678 |
+-------+-----------+
1 row in set (0.00 sec)
答案 0 :(得分:3)
另一种方式
SELECT field_b
FROM my_table_2 m2
WHERE EXISTS (
SELECT my_id FROM my_table
WHERE field_a = 1234 and m2.my_id_2=my_table.my_id
);
答案 1 :(得分:1)
该查询可以重写为简单的连接操作:
SELECT field_b
FROM my_table_2
INNER JOIN my_table ON my_table_2.my_id_2 = my_table.my_id
WHERE field_a = 1234;