简体   繁体   English

SQL查询优化帮助

[英]SQL Query Optimization help

my foundation on SQL is pretty weak so I hope you could bear with me. 我在SQL方面的基础很薄弱,因此希望您能忍受。 I have three tables: contents, categories, and categorization. 我有三个表:内容,类别和分类。 The setup was chosen since some content will belong to one or more categories. 选择该设置是因为某些内容将属于一个或多个类别。

I want to fetch contents and its corresponding categories. 我想获取内容及其相应的类别。

This is an overly-simplified version of the current script, without error-checking routines: 这是当前脚本的过于简化的版本,没有错误检查例程:

$q = "SELECT * FROM contents WHERE contents.foo = 'bar'"
$resource = mysql_query($q);
$categoryFilter = array();

$q2 = "SELECT * FROM categorization WHERE ";
while($content = mysql_fetch_assoc($resource))
{
    $categoryFilter[] = "content_id='" . $content["id"] . "'";
}

if(count($categoryFilter))
{
    $q2 .= implode(" OR ", $categoryFilter);
    mysql_query($q2);
}

That's the gist of it. 这是它的要点。 I hope you get what I am trying to do. 我希望你能得到我想要做的。 I don't know if I can actually use JOINS the content_id may be present in multiple rows in categorization . 我不知道我是否真的可以使用JOINS, content_id可能在categorization出现在多行中。 So what I did was to simply append multiple OR 's, trying to fetch items one by one. 因此,我要做的就是简单地追加多个OR ,试图一一读取项。 I really would not like to use multiple queries in this scenario. 我真的不想在这种情况下使用多个查询。 I hope anyone could suggest an approach 我希望任何人都可以建议一种方法

Thanks for your time 谢谢你的时间

One query should be enough to fetch data from all three tables: 一个查询应该足以从所有三个表中获取数据:

SELECT categories.category_id #, other fields
FROM contents
INNER JOIN categorization ON contents.content_id = categorization.content_id
INNER JOIN categories ON categorization.category_id = categories.category_id
WHERE contents.content_id = 1 # AND other filters

Tweak the columns in the SELECT clause and/or conditions in WHERE clause according to your needs. 根据需要调整SELECT子句中的列和/或WHERE子句中的条件。

If I understand it correctly, you can do this in one sql statement 如果我理解正确,则可以在一个sql语句中执行此操作

SELECT *
FROM contents t1 
JOIN categorization t2
WHERE t1.content_id = t2.content_id AND t1.foo = 'bar'

Also ensure that content_id is indexed both in 'content' and 'categorization'. 还要确保在“内容”和“分类”中都为content_id编制索引。 You may find it worthwhile indexing 'foo' aswell, but it depends on how you are actually searching. 您可能会发现它也值得索引“ foo”,但这取决于您实际搜索的方式。

This should do the same thing as in your example: 这应该与您的示例中的操作相同:

$q = "
    SELECT *
    FROM
        contents c
        categorization ctg ON ctg.content_id = c.id
    WHERE c.foo = 'bar'
";

$result = mysql_query($q);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM