[英]MySQL how do I combine these tables?
我有三張桌子:
blog_posts
int id (auto increment)
varchar(255) title
text content
blog_tags
int id (auto increment)
varchar(63) name
blog_posttags
int id (auto increment)
int post_id
int tag_id
我如何獲得(最好是盡可能少的查詢)這些數據,如具有以下結構的多維數組?
我可以弄清楚如何從數據庫中創建數組,但不知道如何在不查詢我收到的每個博文來查看哪些標簽屬於它的情況下完成這樣的操作。
$blogposts = array(
array(
'id' => 0,
'title' => 'blogpost title',
'content' => 'blogpost content',
'tags' => array(
'tagname1', 'tagname2', 'tagname3', ...,
)
),
... (multiple blogposts because WHERE condition may return more than 1)
)
我想我必須使用UNION
或JOIN
或類似的東西,但我對高級MySQL語句並不熟悉。
編輯:您可以假設tag_id
在blog_posttags
也存在於blog_tags
,同去與post_id
和blog_posts
。
您可以使用MySQL的GROUP_CONCAT
函數在單個查詢中獲取所有標記:
SELECT a.id
,a.title
,a.content
,( SELECT GROUP_CONCAT(b.name)
FROM blog_tags b
JOIN blog_posttags c
ON b.id = c.tag_id
WHERE c.post_id = a.id
) AS tags
FROM blog_posts a
將連接標簽,如:
id title content tags
-------------------------------------------
1 Blog 1 blah blah blah funny,work
2 Next Post yadda yadda school,work
它返回一個這樣的數組:
$blogposts = array(
array(
'id' => 0,
'title' => 'blogpost title',
'content' => 'blogpost content',
'tags' => 'tagname1,tagname2,tagname3'
),
//etc
);
然后你只需要運行這樣的循環來拆分逗號分隔的標記字符串
foreach($blogposts as $k => $v){
$blogposts[$k]['tags'] = explode(',', $v['tags']);
}
下面是一個示例SQL Fiddle,其中包含一些虛擬標簽和帖子,我曾在發布之前對其進行測試
編輯
以下是在不使用子查詢的情況下實現相同結果的另一種方法:
SELECT a.id
,a.title
,a.content
,GROUP_CONCAT(c.name) AS tags
FROM blog_posts a
JOIN blog_posttags b
ON a.id = b.post_id
JOIN blog_tags c
ON b.tag_id = c.id
GROUP BY a.id
獲取與帖子匹配的標簽信息的基本查詢將如下所示。
Select bp.Id, bp.title, bp.content, bt.name
from blog_posts bp
JOIN blog_posttags bpt ON bp.Post_id = bpt.post_id
JOIN blog_tags bt ON bt.tag_id = bpt.tag_id
這將為您提供多行,每行匹配一個帖子到一個標簽。 將標記分組到數組中並不是您可以在SQL端執行的操作,但您可以這樣做
Select bt.name
from blog_posts bp
JOIN blog_posttags bpt ON bp.Post_id = bpt.post_id
JOIN blog_tags bt ON bt.tag_id = bpt.tag_id
WHERE bp.Id = 12345
作為單獨的查詢來獲取給定帖子的標簽。 在這兩者之間,您應該能夠在應用程序級別創建嵌套數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.