使用WHERE子查询改进SQL

时间:2011-08-03 12:41:36

标签: mysql sql

我有这个SQL工作正常,虽然有点慢。理想情况下,想在where子句中使用额外的子查询,例如此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

2 个答案:

答案 0 :(得分:1)

此查询不符合您的需求吗? (基本上,使用连接来获取国家,而不是使用子选择。)

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

答案 1 :(得分:0)

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