0

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') 
Sandeep Kumar
  • 13,799
  • 21
  • 74
  • 110

2 Answers2

1

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.)

Nikola Markovinović
  • 18,963
  • 5
  • 46
  • 51
  • will there be any performance improvement by replacing sub-query with derived table? – Sandeep Kumar Aug 03 '12 at 12:23
  • @Sandy [This man explained it](http://stackoverflow.com/questions/1200295/sql-join-vs-in-performance). It also depends heavily on your sql engine; there is no silver bullet. Best is to test it yourself. – Nikola Markovinović Aug 03 '12 at 12:28
0

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
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50