避免一对多关系中的许多查询的最佳方法
我有一个文章表,其中包含 id、标题等。
我有另一个表,其中包含每篇文章的所有图像,称为 imagePath,它存储图像的路径。它包含 id、path、articleId 等。
每篇文章可以有很多图像。
我想以尽可能最好的方式获取文章及其相关图像。
选项 1:
SELECT a.id,a.title,b.path
FROM articles a, imagepaths b
WHERE a.id=b.articleId
LIMIT 10;
问题:这会产生重复的结果。 选项 2中的每个图像都会重复文章行
:
SELECT *
FROM imagepath
WHERE articleId='111111'
但必须对每个图像执行此操作。我的页面显示了数百篇文章的文章摘要。假设 100 篇文章,每篇文章有 2 个图像,这将需要对文章表进行 1 次调用,对图像路径表进行 200 次调用。
你会怎么做?
**更新**
像这样使用 GROUP_CONCAT() 怎么样:
select a.id,a.title,GROUP_CONCAT(b.imagePath) from articles a
inner join imagePaths b on a.id=b.unique_id
group by a.id limit 3
结果:
id | title | GROUP_CONCAT(b.imagePath)
1 | 'title1' | path1,path2
2 | 'title2' | path3,path4,path5
3 | 'title3' | path6
这给出了我的所有信息需要。但查询需要0.25s。考虑到我可能需要运行很多查询,我有点慢。
我们能做的就是最好的吗?
I have a table of articles with contains id,title among others.
I have another table which contains all the images for each articles called imagePath which stores the path for images. It contains id,path,articleId among others.
Each article can have many images.
I want to get article and its associated images in the best way possible.
Option 1:
SELECT a.id,a.title,b.path
FROM articles a, imagepaths b
WHERE a.id=b.articleId
LIMIT 10;
Problem: This gives duplicate results. Article rows are duplicated for each image in imagepath
Option 2:
SELECT *
FROM imagepath
WHERE articleId='111111'
But this has to be done for each image. I have pages which shows article abstracts for hundreds of articles. Assuming 100 articles with 2 images each this would take 1 call to article table and 200 calls to imagepath table.
How would you do this?
**Update**
How about using GROUP_CONCAT() like this:
select a.id,a.title,GROUP_CONCAT(b.imagePath) from articles a
inner join imagePaths b on a.id=b.unique_id
group by a.id limit 3
Result:
id | title | GROUP_CONCAT(b.imagePath)
1 | 'title1' | path1,path2
2 | 'title2' | path3,path4,path5
3 | 'title3' | path6
this gives all the info I need. But the query takes 0.25s. I bit slow considering I might have to run many queries.
Is the best we can do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
选项 1 不会为您提供重复的结果 - 仅当表中已有重复的数据时。它为每个 a.title 提供了多个 b.path,但仅此而已。
例如:
...会给你这个结果:
选项 1 在大多数情况下都是我会做的方式。我会以这种方式重新格式化查询:
更新:
Ofc 您可以按 Id 将其分组:
但是您的结果将如下所示:
如果这就是您想要的...就这样做! ;-)
Option 1 doesn't give you duplicate results - only if you already have duplicate data in the tables. It gives you more than one b.path for each a.title, but thats about it.
For example:
...will give you this result:
Option 1 is in most cases the way I would do it. I'd reformat the query this way:
Update:
Ofc you can group it by Id:
But then your result will look like this:
If this is what you want... just do it! ;-)