Sandy
Sandy

Reputation: 14133

translating sql sub query to join

I had a long query, I short it out by using joins instead and resultant query is as below but still it has sub query. How to convert this sub query to join

SELECT 
    pav.post_id as Id, img.path as Path, attr.name as Name, pc.title as Category, pav.value_text as Valuess, post.created_on as createdOn 
FROM 
    postings post inner join post_attributes_values pav on post.post_id = pav.post_id
    left outer join images img on post.post_id = img.post_id and img.sequence='1' 
    inner join attributes attr on pav.attr_id = attr.attr_id 
    inner join categories_parent_categories pc on attr.cat_id = pc.category_id 
where 
    pav.post_id in  (select distinct post_id from post_attributes_values where value_text = 'SFX') 

Upvotes: 0

Views: 169

Answers (2)

Nikola Markovinović
Nikola Markovinović

Reputation: 19356

After reading your last comment to Matei's answer I have come to realize that you actually want ALL the posts where one of the attributes has value of 'SFX'. If I understood correctly, your only alternative is to add derived table and join by post_id:

SELECT pav.post_id     AS Id,
       img.path        AS Path,
       attr.name       AS Name,
       pc.title        AS Category,
       pav.value_text  AS Valuess,
       post.created_on AS createdOn
FROM   postings post
       INNER JOIN post_attributes_values pav
               ON post.post_id = pav.post_id
       LEFT OUTER JOIN images img
                    ON post.post_id = img.post_id
                       AND img.sequence = '1'
       INNER JOIN attributes attr
               ON pav.attr_id = attr.attr_id
       INNER JOIN categories_parent_categories pc
               ON attr.cat_id = pc.category_id
       INNER JOIN
       (
             SELECT DISTINCT post_id
             FROM   post_attributes_values
             WHERE  value_text = 'SFX'
       ) sfxPosts
               ON pav.post_id = sfxPosts.post_id

(Query reformatted thanks to instant sql formatter.)

Upvotes: 1

Mihai Matei
Mihai Matei

Reputation: 24276

Maybe this? Please test it

SELECT 
    pav.post_id as Id, img.path as Path, attr.name as Name, pc.title as Category, pav.value_text as Valuess, post.created_on as createdOn 
FROM 
    postings post 
  inner join post_attributes_values pav on post.post_id = pav.post_id AND pav.value_text = 'SFX'
  left outer join images img on post.post_id = img.post_id and img.sequence='1' 
  inner join attributes attr on pav.attr_id = attr.attr_id 
  inner join categories_parent_categories pc on attr.cat_id = pc.category_id

Upvotes: 0

Related Questions