简体   繁体   中英

Nested Left Join query not working

I am trying to left join a query and it fails with the message :

Unknown column 'seller_product.seller_product_id' in 'on clause'

Here is the query:

SELECT sp.seller_product_id FROM seller_product 
LEFT JOIN ( 
         SELECT spov.seller_product_id 
          FROM seller_product_option_value spov 
          WHERE spov.active = 1 
          AND spov.seller_product_id IN (  2567 ) ) AS option_query 
  ON seller_product.seller_product_id = option_query.spov.seller_product_id

You need to alias your table,try this:

SELECT sp.seller_product_id FROM seller_product sp
LEFT JOIN ( 
         SELECT spov.seller_product_id 
          FROM seller_product_option_value spov 
          WHERE spov.active = 1 
          AND spov.seller_product_id IN (  2567 ) ) AS option_query 
  ON sp.seller_product_id = option_query.spov.seller_product_id

Don't nest the left joins. You can filter in the ON clause:

SELECT sp.seller_product_id
FROM seller_product sp LEFT JOIN
     seller_product_option_value spov
     ON sp.seller_product_id = spov.seller_product_id AND
        spov.active = 1 AND
        spov.seller_product_id IN (  2567 );

Avoiding subqueries in the FROM clause is particularly important in MySQL, because it materializes the subquery. That adds overhead and precludes the use of indexes for the JOIN .

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