我有我用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查詢寫的嗎?
我發現了一個類似的問題here但它並沒有完全解決我的問題,我不確定它是否是最有效的方法。
的2個表是blogs
和comments
其中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
要插入兩個表,您是否需要至少兩個sql語句(一個表)。你知道嗎?否則,需要存儲過程或觸發器。是一個程序還是觸發一個有效的解決方案? – danihp
@danihp我的主要目標是儘可能聯繫那個數據庫服務器。所以我可以幫助我做到這一點。 – sameold
@danihp我應該指出,我試圖結合的2個查詢是相關的,但不完全相同。第二個查詢只使用第一個查詢中的'blog_id'。 – sameold