带有多个嵌套 SELECT 的 MySQL INSERT
这样的查询可以吗? MySQL 给我一个语法错误。具有嵌套选择的多个插入值...
INSERT INTO pv_indices_fields (index_id, veld_id)
VALUES
('1', SELECT id FROM pv_fields WHERE col1='76' AND col2='val1'),
('1', SELECT id FROM pv_fields WHERE col1='76' AND col2='val2')
Is a query like this possible? MySQL gives me an Syntax error. Multiple insert-values with nested selects...
INSERT INTO pv_indices_fields (index_id, veld_id)
VALUES
('1', SELECT id FROM pv_fields WHERE col1='76' AND col2='val1'),
('1', SELECT id FROM pv_fields WHERE col1='76' AND col2='val2')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(2)
梦里寻她2024-12-13 20:38:07
当您有这样的子查询时,它必须仅返回一列和一行。如果您的子查询只返回一行,那么您需要在它们周围加上括号,正如 @Thor84no 注意到的那样。
如果它们返回(或可能返回)多于行,请尝试以下操作:
INSERT INTO pv_indices_fields (index_id, veld_id)
SELECT '1', id
FROM pv_fields
WHERE col1='76'
AND col2 IN ('val1', 'val2')
或者如果您的条件非常不同:
INSERT INTO pv_indices_fields (index_id, veld_id)
( SELECT '1', id FROM pv_fields WHERE col1='76' AND col2='val1' )
UNION ALL
( SELECT '1', id FROM pv_fields WHERE col1='76' AND col2='val2' )
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我刚刚测试了以下内容(有效):
insert into test (id1, id2) values (1, (select max(id) from test2)), (2, (select max(id) from test2) );
我想问题是你的选择周围没有 () ,因为没有它这个查询就无法工作。
I've just tested the following (which works):
insert into test (id1, id2) values (1, (select max(id) from test2)), (2, (select max(id) from test2));
I imagine the problem is that you haven't got ()s around your selects as this query would not work without it.