2012-08-25 38 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