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

标签 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')
    }
}

edit:

The reason I'm doing it is because I want to void queries inside loop. For example, I'm generating 100 rows and saving them to files.

$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 次,我该如何解决这个问题?

最佳答案

这是一种可怕的做事方式,但我相信这就是您正在寻找的: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 时。

关于MySQL 在一个查询中选择多行的相关数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13419200/

相关文章:

mysql - "Repeatable read"与乐观

mysql - SQL 内连接 - 性能改进

mysql - 更新子查询的 WHERE 子句中的 UNION

mysql - 选择一行没有重复条目

mysql - 获取一种且只有一种类型的记录

css - 如何确保选择选项文本在 IE 中居中对齐?

sql - 如何将表别名传递给 SQL 中的子子查询?

php - 根据数据库中的值在 div 中显示图像

php - 根据数组写入行数

mysql - 获得每个用户所有帖子的总投票数