[英]Combining multiple queries into a single query
我有用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:多關系,其中每個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
如果不存在,您可以使用此技術插入行:
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
表,您可以使用相同的技術。 如果插入是dued,則可以使用LAST_INSERT_ID()獲取第二個查詢的Blog id
(如果不是,則需要新查詢)。
這只是一個重要的開始點,也許你可以將你的4個查詢減少到3個。 歡迎任何評論以確定最終解決方案。
如您所知,MySQL沒有MERGE語句。 我認為替換與你的requeriments不符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.