开发者

Improve SQL with WHERE sub query

I have this SQL that works fine although a little slow. Ideally would like to have the extra sub query in the where clause something like this AND country_iso = "uk".

SELECT c.content_name, c.content_telephone, c.content_address1
    (SELECT w.weblink_url FROM weblinks w WHERE w.content_id = c.content_id ORDER BY w.weblink_ordering, w.weblink_id ASC LIMIT 1) 
    AS content_url,                                                          
     (SELECT country_name FROM countries WHERE country_id = c.country_id LIMIT 1)
    AS country_name,                                                                                                                     
     (SELECT country_iso FROM countries WHERE country_id = c.country_id LIMIT 1)
    AS country_iso
    FROM catcontents cc                                                     
    LEFT JOIN content c ON c.content_id = cc.content_id                                                         
  开发者_开发技巧  WHERE cc.category_id = 7 
    AND (SELECT country_iso FROM countries WHERE country_id = c.country_id LIMIT 1) = 'uk' 
ORDER BY cc.catcontent_ordering ASC, c.content_name ASC


Would this query not suit your needs? (basically, use joins to get the country, instead of sub-selects.)

SELECT
    c.content_name,
    c.content_telephone,
    c.content_address1,

    countries.country_name,
    countries.country_iso,

    (
        SELECT w.weblink_url 
        FROM weblinks w 
        WHERE w.content_id = c.content_id 
        ORDER BY w.weblink_ordering, w.weblink_id ASC 
        LIMIT 1
    ) content_url

FROM catcontents cc
LEFT JOIN content c ON c.content_id = cc.content_id
JOIN countries ON countries.country_id = c.country_id

WHERE cc.category_id = 7
AND countries.country_iso = 'uk'

ORDER BY cc.catcontent_ordering ASC, c.content_name ASC


SELECT  c.content_name,
        c.content_telephone,
        c.content_address1,
        w.weblink_url content_url,
        country_name,
        country_iso
FROM catcontents cc                                                     
LEFT JOIN content c ON c.content_id = cc.content_id
LEFT JOIN weblink_url w ON w.content_id = c.content_id
JOIN   countries ON   country_id = c.country_id
                  AND  country_iso = 'uk'                                    
WHERE cc.category_id = 7 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜