INSERT,子查询,VALUES

时间:2015-02-26 10:23:30

标签: c# sql postgresql

此查询从othes表中插入表值(它返回的行数超过1行)

INSERT INTO metric_values(mv_db_id, mv_cat_id)
    (SELECT DISTINCT dbs_id, cat_id FROM
       (SELECT DISTINCT cat_id, dbs_id FROM categories
           INNER JOIN users ON (cat_id = us_category_id)
              INNER JOIN hits ON (us_id = h_user_id)
                 INNER JOIN dbs ON (h_db_id = dbs_id)
           WHERE h_datetime = '2009-09-28'
              GROUP BY cat_id, dbs_id)foo)

但我还有一些变量(mv_metric_id,mv_period_id,mv_period_startdate),这是我从程序(c#)收到的值。有谁知道如何使用此查询插入此变量?

这样的事情:

INSERT INTO metric_values(mv_metric_id, mv_period_id, mv_period_startdate, mv_db_id, mv_cat_id)
 VALUES (1, 1, '2009-09-28', (SELECT DISTINCT dbs_id, cat_id
                              FROM (SELECT DISTINCT cat_id, dbs_id
                                    FROM categories
                                    INNER JOIN users ON (cat_id = us_category_id)
                                    INNER JOIN hits ON (us_id = h_user_id)
                                    INNER JOIN dbs ON (h_db_id = dbs_id)
                                    WHERE h_datetime = '2009-09-28'
                                    GROUP BY cat_id, dbs_id)foo))

1 个答案:

答案 0 :(得分:0)

您可以将自己的值放在最外面的SELECT子句中,例如:

INSERT INTO metric_values(mv_metric_id, mv_period_id, mv_period_startdate, mv_db_id, mv_cat_id)
    (SELECT DISTINCT MYDATA1, MYDATA2, MYDATA3, dbs_id, cat_id FROM
       (SELECT DISTINCT cat_id, dbs_id FROM categories
           INNER JOIN users ON (cat_id = us_category_id)
              INNER JOIN hits ON (us_id = h_user_id)
                 INNER JOIN dbs ON (h_db_id = dbs_id)
           WHERE h_datetime = '2009-09-28'
              GROUP BY cat_id, dbs_id)foo)

当然,这会使整行DISTINCT因此可能重新组合您的SELECT条款。