将2个CTE替换为1个

时间:2018-02-20 13:21:22

标签: sql postgresql

我在postgresql上有以下代码:

    WITH CTE1 AS
(
SELECT
               value_1
              ,position
              ,value_3
              ,value_4
              ,value_5
From tabl_1
WHERE position = 1 
)

WITH CTE2 AS
(
SELECT
               value_1
              ,position
              ,value_3
              ,value_4
              ,value_5
From tabl_1
WHERE position = 2 
)   

INSERT INTO tbl_2
SELECT
CTE1.value_2 = IP_1
CTE2.value_2 = IP_2

FROM table_3 er
                LEFT JOIN CTE1 ON CTE1.value_1 = er.value_1 AND CTE1.value_3 = er.value_3
                LEFT JOIN CTE2 ON CTE2.value_1 = er.value_1 AND CTE2.value_3 = er.value_3

我在单独的CTE中计算IP_1,IP-2的值,但我还不知道如何在一个CTE上替换2个CTE?或者其他一些方式。

1 个答案:

答案 0 :(得分:1)

复制您的代码,这似乎有很多错误:

  • 插入的两列之间没有逗号;
  • value_2不在您的任何一个CTE中。

这可以重构以删除所有CTE:

<?php
          $total = 0;
          foreach($_SESSION["products"] as $product){       
            $product_name = $product["product_name"]; 
            $products = implode(',', $product_name);
          }
            $sql = "INSERT INTO tablename (productname)
            VALUES ($products)";

    ?>