如何使用我在JOIN语句的子查询中定义的临时表?

时间:2017-06-23 14:50:31

标签: sql postgresql

这是我的代码:

    SELECT 
<columns> 
FROM
(Subquery code) as relevantcustomers,
db_sales, 
JOIN relevantcustomers on relevantcustomers.id = sales.customer_id

为什么SQL不允许我这样做?

1 个答案:

答案 0 :(得分:0)

你有:

SELECT 
  <columns> 
FROM (Subquery code) as relevantcustomers, -- data from a subquery
db_sales, -- cross join a table named db_sales, but a comma too many
JOIN relevantcustomers -- joining a table called relevantcustomers
  on relevantcustomers.id = sales.customer_id -- conflict: which relevantcustomers?

你想:

SELECT 
  <columns> 
FROM (Subquery code) as relevantcustomers
JOIN db_sales on relevantcustomers.id = sales.customer_id;

或与WITH子句相同:

WITH relevantcustomers AS (Subquery code)
SELECT 
  <columns> 
FROM relevantcustomers
JOIN db_sales on relevantcustomers.id = sales.customer_id;