基于多个id将多行插入sql

gupuwyp2  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(290)

我想为每个用户插入三个值或三行。我知道我可以使用以下查询

INSERT INTO subscriptions(id_account, subscription) 
SELECT id_account, 'subscriptionVAlue' FROM   unnest ('{123,456,789}'::int[]) id;

为列表中的每个id插入一行。但我想要的是这样的东西

INSERT INTO subscriptions (account_id, subscription, i18nkey) 
VALUES (id, 'subscription1', 'translation1')
VALUES (id, 'subscription2', 'translation2')
VALUES (id, 'subscription3', 'translation3')
where id in (123,1234,410,4512);

我知道这是一个很糟糕的问题,但我希望有类似的行为。有可能吗?

t98cgbkg

t98cgbkg1#

你可以用 cross join :

INSERT INTO subscriptions (account_id, subscription, i18nkey) 
    SELECT a.account_id, subscription, i18nkey
    FROM (SELECT 'subscription1' as subscription, 'translation1' as i18nkey UNION ALL
          SELECT 'subscription2', 'translation2' UNION ALL
          SELECT 'subscription3', 'translation3'
         ) x CROSS JOIN
         (SELECT 123 as account_id UNION ALL SELECT 1234 UNION ALL
          SELECT 410 UNION ALL SELECT 4512
         ) a;
``` `unnest()` 不是mysql语法。你也可以做类似的事情 `unnest()` . 尽管您可能需要一个 `FROM` 条款(如 `FROM dual` )对于子查询。

相关问题