MySQL在一个查询中为多行选择相关数据
我想为多行选择相关文章,并在一个查询中按id对它们进行分组。可能吗 差不多MySQL在一个查询中为多行选择相关数据,mysql,select,correlated-subquery,Mysql,Select,Correlated Subquery,我想为多行选择相关文章,并在一个查询中按id对它们进行分组。可能吗 差不多 id title -------------------------- 1 mysql websites 2 html tips 3 mysql tricks 4 javascript tutorial 5 mysql queries 6 javascript framework 结果是 SELECT id, title FROM articles
id title
--------------------------
1 mysql websites
2 html tips
3 mysql tricks
4 javascript tutorial
5 mysql queries
6 javascript framework
结果是
SELECT
id, title
FROM
articles
WHERE
title LIKE (TITLE_OF_CURRENT_ROW)
AND id IN (1,4)
GROUP BY
id;
上面的相关查询将重复100次,我怎样才能做到这一点呢?这与您所追求的类似吗
这是一种可怕的做事方式,但我相信这正是你想要的: 它之所以可怕,是因为MySQL不能使用恰好位于
title
上的任何索引,因为a)您只对匹配第一个单词感兴趣,b)您想匹配其他条目中标题任何位置的第一个单词
MySQL无法为像
%cheese%
这样的搜索创建索引,全文索引和搜索可以用于cheese%
,特别是如果您使用布尔模式。您在(1,4)中有id,但您希望的结果有所有id。。。我不明白,结果正是我所期望的。但是我想在一个查询中完成它。此外,关键字未知,仅提供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')
}
}
$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']);
}
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