使用FROM子句将两个查询连接到子查询中

时间:2018-04-16 04:30:57

标签: sql sql-server

我正在尝试使用FROM子句将两个查询组合成一个不相关的表达式。我试图模仿书中的课程计划示例,但我一直收到有关我的加入的错误。

错误是:

  

Msg 156,Level 15,State 1,Line 6
  关键字“JOIN”附近的语法不正确。

我认为这意味着我的态度非常接近。

这两个查询是:

     SELECT Product.product_id, product.product_name
     FROM Product
     JOIN Sells on Sells.product_id = product.product_id
     GROUP BY product.product_id, product.product_name
     HAVING COUNT(sells.store_location_id) = 5;


     SELECT Product.product_name, Sizes.Size_option
     FROM Product
     JOIN Available_in ON Product.product_id = Available_in.product_id
     JOIN Sizes ON  Available_in.sizes_id = Sizes.sizes_id

我的当前代码是:

     SELECT Product.product_name, Sizes.Size_option
     FROM (SELECT Sells.product_id
          FROM Sells
          JOIN Sells on Sells.product_id = product.product_id
          GROUP BY Sells.product_id
          HAVING COUNT(*) = 5)
     JOIN Available_in ON Product.product_id = Available_in.product_id 
     JOIN Sizes ON Available_in.Sizes_id = Sizes.sizes_id;

3 个答案:

答案 0 :(得分:2)

"产品"在派生表之外不可用于加入,修改代码如下: -

 SELECT Temp.product_name, Sizes.Size_option
 FROM (SELECT Sells.product_id
      FROM Sells
      JOIN Sells on Sells.product_id = product.product_id
      GROUP BY Sells.product_id
      HAVING COUNT(*) = 5) Temp
 JOIN Available_in ON Temp.product_id = Available_in.product_id 
 JOIN Sizes ON Available_in.Sizes_id = Sizes.sizes_id;

答案 1 :(得分:0)

语法错误可能是由于缺少子查询(SELECT sells....)的别名。我会通过将第一个查询转换为子查询(在5个位置销售的产品)并给它别名Product并将其加入第二个查询来接近它:

SELECT Product.product_name, Sizes.Size_option
FROM 
-- first query --
(SELECT Product.product_id, product.product_name
 FROM Product
 JOIN Sells on Sells.product_id = product.product_id
 GROUP BY product.product_id, product.product_name
 HAVING COUNT(sells.store_location_id) = 5) Product

 JOIN Available_in ON Product.product_id = Available_in.product_id
 JOIN Sizes ON  Available_in.sizes_id = Sizes.sizes_id

答案 2 :(得分:0)

您当前的查询有多个错误,因为您在子查询中有两次sales

如果我理解正确,您可以将查询编写为:

 SELECT p.product_name, s.Size_option
 FROM (SELECT s.product_id
       FROM Sells s 
       GROUP BY s.product_id
       HAVING COUNT(*) = 5
      ) sp JOIN
      Available_in a
      ON sp.product_id = a.product_id JOIN
      Sizes s
      ON ai.Sizes_id = s.sizes_id JOIn
      Products p
      ON p.product_id = a.product_id;