将sql子查询转换为join

时间:2012-08-03 10:48:12

标签: sql subquery

我有一个很长的查询,我通过使用连接来缩短它,结果查询如下,但它仍然有子查询。如何将此子查询转换为加入

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

2 个答案:

答案 0 :(得分:1)

在阅读了您对Matei的回答的最后评论后,我意识到您确实想要所有帖子,其中一个属性具有'SFX'的值。如果我理解正确,你唯一的选择是添加派生表并通过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

(感谢instant sql formatter重新格式化查询。)

答案 1 :(得分:0)

也许这个?请测试一下

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