简体   繁体   中英

Error Using Alias in subquery to retrieve results

Here is the scenario and question:

Marcus also travels internationally, and he is interested in considering some products to purchase. Because his employer sends him to various locations throughout the world with little notice, he only wants to consider a product if it is available in all store locations, and is not interested in products that are available in some but not all store locations. This way, should he decide to purchase a product, he has the assurance that can purchase it at any of the locations. Lastly, he is interested in viewing the sizing options for each product that meets his criteria.

I used a subquery within the WHERE clause and got the output displaying only the 2 products (in all store locations) with the respective size options:

SELECT Sizes.size_option,Product.product_name
FROM Sizes
JOIN Available_in ON Available_in.sizes_id = Sizes.sizes_id
JOIN Product ON Product.product_id = Available_in.product_id
WHERE Product.product_id IN
      ( SELECT Product.product_id
        FROM Product
        JOIN SELLS ON Sells.product_id = Product.product_id
        GROUP BY Product.product_id
        HAVING COUNT(Sells.store_location_id) = 5);

For the next question, I have to rearrange the subquery using a Alias and add the subquery to FROM clause and this is what I did:

SELECT SO.size_option,Product.product_name
FROM (SELECT Product.product_id
      FROM Product
      JOIN SELLS ON Sells.product_id = Product.product_id
      GROUP BY Product.product_id
      HAVING COUNT(Sells.store_location_id) = 5)SO
JOIN Available_in ON Available_in.sizes_id = SO.sizes_id
JOIN Product ON Product.product_id = Available_in.product_id;

I renamed the Sizes table as SO for the alias. Im getting an error that SO.sizes_id is an invalid identifier. This worked when I used it in the Where clause but not working with the FROM clause. Would appreciate some help on how to fix this!

I'm using Oracle SQL Developer to write my queries.

You have not a size_id select in subselect so you can't use for join

  SELECT SO.size_option, Product.product_name
  FROM (SELECT Product.product_id, ????? size_id ????? <<<<<<<<<<<<<<<
        FROM Product
        JOIN SELLS ON Sells.product_id = Product.product_id
        GROUP BY Product.product_id
        HAVING COUNT(Sells.store_location_id) = 5) SO
  JOIN Available_in ON Available_in.sizes_id = SO.sizes_id
  JOIN Product ON Product.product_id = Available_in.product_id;

In join for SO you can use only column selected in subselect that generated the from ( ) SO table

and as suggested by JuanCarlosOropeze you have not size_option too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM