我有我用 ORM 语法编写的代码。它从文件中读取博客评论数据,并将它们插入到blogs
表comments
中。我想把这个 ORM 代码带回 mysql,因为我需要将尽可能多的查询组合成一个查询,而这种优化在 ORM 语言中并不容易。我需要这种优化的原因是因为我正在使用远程服务器,所以查询越少越好。我用mysql伪代码写了下面的代码,因为我有点忘记了mysql。
这是包含所有博客的所有评论的评论文件。from blog url
告诉我这条评论属于哪个博客。
comment text from blog url
------------------------------------------
first comment text first-blog-url
second comment text first-blog-url
third comment text first-blog-url
fourth comment text blog-2-url
fifth comment text blog-2-url
sixth comment text 3rd-blog-url
这是我用来处理文件的 ORM 代码。(在最底部,我添加了表格的描述)。
//I read a comment from the comments file, `comment text` and `from blog url`
//does a blog exist that has 'link' that matches 'from blog url'
$blog = //SELECT FROM blogs where 'link' has value 'first-blog-url'
//if it doesn't exist, create it
if($blog == null){
$blog = INSERT INTO blogs a new record and set 'link' to 'first-blog-url'
}
//then read the id of the (existing or just-created) blog row
$blog_id = $blog->getId();
//then use the $blog_id to insert the comment into the 'comments' table.
//does this comment text already exist for this blog id?
$comment = SELECT FROM comments where `commenttext' has value 'whatever comment text' and 'blogid' has value $blog_id
//if it doesn't exist, create it
if($comment == null){
$comment = INSERT INTO comments a new record and set 'commenttext' to 'the comment text' and 'blogid' to $blog_id.
}
$comment_id = $comment->getId();
所以我的问题是:是否可以在单个 mysql 查询中编写它?
我在这里发现了一个类似的问题,但它并没有完全解决我的问题,而且我不确定这是否是最有效的方法。
这 2 个表是blogs
,comments
其中的每一行comments
都有一个字段blogid
,将其链接到 中的正确博客blogs
。所以它基本上是一个 1:many 关系,其中每一blog
行都可以链接到许多comment
行。它们看起来像这样:
blogs:
id link other fields
--------------------------------------------
1 first-blog-url
2 blog-2-url
3 3rd-blog-url
comments:
id commenttext blogid
-----------------------------
1 random 1
2 comment 1
3 goes 1
4 here 2
5 any 2
6 thing 3