mysql - 使用 WHERE 子查询改进 SQL

标签 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

最佳答案

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

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

关于mysql - 使用 WHERE 子查询改进 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6926597/

相关文章:

php - INSERT IGNORE INTO - 插入的行数

php - 将逗号分隔的字符串拆分为多列到 db - php

MySQL 错误 1064 : near NULL at line 1

sql - 表示日期/时间段

sql - 根据另一个列的值将一个 sql 列拆分为两个

php - 关联数组中最常见的值

mysql - 多列的 SQL 平均值

sql - 复制sql表的最快方法

sql - 查找所有包含列名的表;过滤空

mysql - 在 ComboBox.Item 中隐藏部分 String.Format