2012-08-25 112 views
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查询写的吗?

我发现了一个类似的问题here但它并没有完全解决我的问题,我不确定它是否是最有效的方法。

的2个表是blogscomments其中comments每一行都有一个字段blogid它链接到正确的博客中blogs。所以它基本上是1:多的关系,其中每个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 
+0

要插入两个表,您是否需要至少两个sql语句(一个表)。你知道吗?否则,需要存储过程或触发器。是一个程序还是触发一个有效的解决方案? – danihp

+0

@danihp我的主要目标是尽可能联系那个数据库服务器。所以我可以帮助我做到这一点。 – sameold

+0

@danihp我应该指出,我试图结合的2个查询是相关的,但不完全相同。第二个查询只使用第一个查询中的'blog_id'。 – sameold

回答

3

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

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

正如你可以看到,SELECT子句将返回一个只有一行与要插入的数据只有当数据库中还不存在时。 You can test it at SQLFIDDLE.

要插入到comment表中,您可以使用相同的技术。如果插入的话,您可以获得​​的第二个查询LAST_INSERT_ID()(如果没有,则需要新的查询)。

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

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

+0

我想知道,什么是从双'这是一个错误的表,或一个特殊的关键字? – sameold

+0

那么是否有可能进一步嵌套评论插入,以便博客插入和评论插入都在同一个查询中? – sameold

+0

你需要每个表的插入语句。你不能在同一个语句中插入两个。也许你想要将所有代码封装到[存储过程]中(http://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspx)。 – danihp