我有一个这样的值数组(restaurant_id
不是主键):
[
{restaurant_id:1, day_of_week:0, from_time: "12:00", to_time: "14:00", is_open:false },
{restaurant_id:1, day_of_week:1, from_time: "12:00", to_time: "14:00", is_open:true },
{restaurant_id:1, day_of_week:2, from_time: "12:00", to_time: "14:00", is_open:true },
...
]
每天一次。
我想将它们每个都保存为PostgreSQL
数据库中的新行。
我对这个查询有一次插入:
INSERT INTO schedules (restaurant_id, day_of_week, from_time, to_time, is_open) VALUES ($1, $2, $3, $4, $5) RETURNING schedules;
应该执行7条INSERT
语句,还是可以循环并全部保存在一条语句中?
循环查询是什么?
编辑:
因此,我可以按照建议在一个查询中执行以下操作:
VALUES (?, ?, ?, ? ?),
(?, ?, ?, ? ?),
(?, ?, ?, ? ?),
(?, ?, ?, ? ?),
(?, ?, ?, ? ?),
(?, ?, ?, ? ?),
(?, ?, ?, ? ?)
但是有更好的方法吗?
答案 0 :(得分:2)
您可以发行一张插页。我建议使用参数:
INSERT INTO schedules (restaurant_id, day_of_week, from_time, to_time, is_open)
VALUES (?, ?, ?, ? ?),
(?, ?, ?, ? ?),
. . .
RETURNING *;
答案 1 :(得分:2)
如果所有其他值都是常量(或可从 running 变量派生),则可以使用generate_series()
INSERT INTO schedules (restaurant_id, day_of_week
, from_time, to_time, is_open)
SELECT 1, gs, '10:00','22:00', True
FROM generate_series(0,6) gs
;
generate_series
的文档
https://www.postgresql.org/docs/11/functions-srf.html
答案 2 :(得分:2)
如果这些输入值实际上是JSON数组的一部分,则可以直接使用它:
INSERT INTO schedules (restaurant_id, day_of_week, from_time, to_time, is_open)
select (v ->> 'restaurant_id')::int,
(v ->> 'day_of_week')::int,
(v ->> 'from_time')::time,
(v ->> 'to_time')::time,
(v ->> 'is_open')::boolean
from jsonb_array_elements('
[
{"restaurant_id":1, "day_of_week":0, "from_time": "12:00", "to_time": "14:00", "is_open":"false" },
{"restaurant_id":1, "day_of_week":1, "from_time": "12:00", "to_time": "14:00", "is_open":"true" },
{"restaurant_id":1, "day_of_week":2, "from_time": "12:00", "to_time": "14:00", "is_open":"true" }
]'::jsonb) as t(v);
当然,您需要用适当的参数替换硬编码的字符串值,例如from jsonb_array_elements(cast(? as jsonb))
答案 3 :(得分:1)
插入用户(id,名称,年龄) 价值 (1,'Talha',22), (2,'John',41), (3,'William',32);
我想这会起作用。
答案 4 :(得分:-1)
Kevin Amiranoff, 您可以为此使用mysql的存储过程。
开始 对于我在1 .. 100000 环 向用户插入值(i,“ Talha”,20 + i); 结束循环 承诺; 结束;