如何组合2个Postgres查询

时间:2018-02-12 20:06:13

标签: sql postgresql

SELECT orders.customer
FROM orders
LEFT JOIN uploads
ON uploads.order = orders.id
WHERE uploads.order IS NULL
AND orders.product_type = 'warrior_workout'


INSERT INTO uploads ( id, order, name, url, file_name, is_main ) VALUES
  (DEFAULT, orders.customer, "warrior_workout_nonhomeworkout","https://example.org","6 Week Warrior Workout Non-Home Workout.pdf",true),
  (DEFAULT, orders.customer, "warrior_workout_homeworkout","https://example.org","6 Week Warrior Workout Home Workout.pdf",true),
  (DEFAULT, orders.customer, "men_six_week_summer_shredder","https://example.org","Men's Six Week Summer Shredder.pdf",true);

我有2个postgres查询,我需要将它们合并为一个。

1 个答案:

答案 0 :(得分:2)

我想你想要这个:

INSERT INTO uploads (customer, name, url, file_name, is_main ) 
    SELECT o.customer, v.*
    FROM orders o LEFT JOIN
         uploads u
         ON u.order = o.id CROSS JOIN
         (VALUES ('warrior_workout_nonhomeworkout', 'https://example.org', '6 Week Warrior Workout Non-Home Workout.pdf', true),
                 ('warrior_workout_homeworkout', 'https://example.org', '6 Week Warrior Workout Home Workout.pdf', true),
                 ('men_six_week_summer_shredder', 'https://example.org', 'Men''s Six Week Summer Shredder.pdf', true)
         ) v(name, url, file_name, is_main)
    WHERE u.order IS NULL AND o.product_type = 'warrior_workout';

对于每个缺少上传的客户,都会插入这三个值。