MySQL在一个查询中为多行选择相关数据

时间:2012-11-16 15:05:44

标签: mysql select correlated-subquery

id    title
--------------------------
1     mysql websites
2     html tips
3     mysql tricks
4     javascript tutorial
5     mysql queries
6     javascript framework

我想为多行选择相关文章,并按ID,在一个查询中对其进行分组。这可能吗?

类似

SELECT
    id, title
FROM
    articles
WHERE
    title LIKE (TITLE_OF_CURRENT_ROW)
    AND id IN (1,4)
GROUP BY
    id;

,结果将是

array
(
    // result for id = 1
    0 => array
    (
        0 => array (id => 1, title => 'mysql websites'),
        1 => array (id => 3, title => 'mysql tricks'),
        2 => array (id => 5, title => 'mysql queries')
    ),

    // result for id = 4
    1 => array
    (
        0 => array (id => 4, title => 'javascript tutorial'),
        1 => array (id => 6, title => 'javascript framework')
    }
}

编辑:

我这样做的原因是因为我想使queries inside loop无效。例如,我正在生成100行并将其保存到文件中。

$result = $mysql->query("SELECT id, title FROM articles LIMIT 100");

while($row = $result->fetch_assoc()) {

    $related_result = $mysql->query("SELECT id, title FROM articles WHERE title LIKE '%".$row['title']."%' AND id != ".$row['id']);

    // while... get related data

    save_data_to_file($row['id'], $row['title'], $related['ids'], $related['titles']);
}

上面的相关查询会重复100次,我该怎么走?

2 个答案:

答案 0 :(得分:1)

这是一种可怕的做事方式,但我相信这就是你要找的东西:http://sqlfiddle.com/#!2/53465/8

SELECT
    articles.id,
    articles.title,
    related.id as rel_id,
    related.title as rel_title
FROM
    articles
LEFT JOIN
  articles AS related
ON
  related.title LIKE CONCAT('%', SUBSTRING_INDEX(articles.title, ' ', 1), '%')
AND    # update: this needs to be AND, not WHERE
  related.id != articles.id
ORDER BY
  articles.title, related.title

可怕的原因是MySQL无法使用恰好位于title上的任何索引,因为a)您只对匹配第一个单词感兴趣,并且b)您希望匹配第一个单词在其他条目中的标题的任何位置。

MySQL无法为%cheese%等搜索创建索引,FULLTEXT索引和搜索可以用于cheese%,尤其是在使用BOOLEAN MODE时。

答案 1 :(得分:0)

它与你之后的类似吗?

http://sqlfiddle.com/#!2/15414/11

相关问题