1

我有我用 ORM 语法编写的代码。它从文件中读取博客评论数据,并将它们插入到blogscomments中。我想把这个 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 个表是blogscomments其中的每一行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
4

1 回答 1

3

如果不存在,您可以使用此技术插入行:

INSERT INTO blogs (link)
select 'first-blog-url' 
from dual
where not exists
( select 1
  from blogs
  where  link = 'first-blog-url'
);

如您所见,select 子句将仅返回一行,其中仅当数据库中尚不存在数据时才插入数据。您可以在 SQLFIDDLE 上对其进行测试。

要插入comment表格,您可以使用相同的技术。如果插入到期,您可以使用LAST_INSERT_ID()Blog id获取第二个查询(如果没有,您需要一个新查询)。

这只是一个开始点,也许您可​​以将 4 个查询减少到 3 个。欢迎任何评论以找出最终解决方案。

如您所知,MySQL 没有 MERGE 语句。我认为替换不符合您的要求。

于 2012-08-25T18:38:11.827 回答