2012-08-03 68 views
0

我有一个很长的查询,我通过使用连接将其缩短出来,而生成的查询如下,但它仍然有子查询。如何转换这个子查询加入翻译sql子查询加入

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

是不同的必要吗?您是否搜索具有值'SFX'的特定属性或任何属性会执行? – 2012-08-03 10:52:16

+0

@NikolaMarkovinović:桌子的设计就像是有必要的。 – 2012-08-03 11:02:43

+0

独特不应该在子查询中不需要,因为您只是在检查.... – 2012-08-03 11:37:24

回答

1

阅读你最后的留言马太的回答后,我已经认识到,你真正想要所有职位其中的一个属性有“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。)

+0

将通过用派生表替换子查询来改善性能吗? – 2012-08-03 12:23:20

+0

@Sandy [此人解释](http://stackoverflow.com/questions/1200295/sql-join-vs-in-performance)。它也很大程度上取决于你的sql引擎;没有银弹。最好的是自己测试一下。 – 2012-08-03 12:28:42

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 
+0

'pav'被提及两次。您可能想要删除最后一次发生。 – 2012-08-03 10:57:26

+0

对..我没有看到它:)谢谢尼古拉 – 2012-08-03 10:58:54

+0

我已经尝试过,但返回的行并不如预期。 – 2012-08-03 11:04:30