2013-03-22 52 views
1

我目前正在嘗試檢索最新的帖子及其相關帖子(每個帖子的x號碼)。我手上有以下查詢:用多列填充MySQL嵌套

SELECT id, title, content 
     (SELECT GROUP_CONCAT(title) FROM posts  -- Select title of related posts 
     WHERE id <> p.id AND id IN (     
      SELECT p_id FROM tagsmap     -- Select reletad post ids from tagsmap 
      WHERE t_id IN (
       SELECT t_id FROM tagsmap    -- Select the tags of the current post 
       WHERE p_id = p.id) 
      ) ORDER BY id DESC LIMIT 0, 3) as related 
FROM posts as p ORDER BY id DESC LIMIT 5 

我的數據庫結構很簡單:職位表。一個標籤表。還有一個tagsmap表,我將帖子與標籤相關聯。

這個查詢工作正常(雖然我不知道它的性能,因爲我沒有在表中有很多行 - 也許解釋可以幫助我,但現在不是這樣)。

我真正需要的是檢索相關職位的ID以及職位。

所以我想做SELECT GROUP_CONCAT(title), GROUP_CONCAT(id),但我知道這會導致錯誤。那麼在這種情況下檢索id和標題的最佳方式是什麼?我不想重寫整個子查詢來檢索id。應該有另一種方式。

編輯

SELECT p1.id, p1.title, p1.content, 
    group_concat(DISTINCT p2.id) as 'P IDs', 
    group_concat(DISTINCT p2.title) as 'P titles' 
FROM posts as p1 
LEFT JOIN tagsmap as tm1 on tm1.p_id = p1.id 
LEFT JOIN tagsmap as tm2 on tm2.t_id = tm1.t_id and tm1.p_id <> tm2.p_id 
LEFT JOIN posts as p2 on p2.id = tm2.p_id 
GROUP BY p1.id 
ORDER BY p1.id desc limit 5; 

這到底是什麼人,我使用的查詢。我刪除了Where子句,因爲它是不必要的,並且使用LEFT JOIN而不是JOIN,否則它會忽略沒有標籤的帖子。最後將DISTINCT添加到group_concat,因爲它連接了重複行(例如,如果某個帖子具有多個具有相關帖子的通用標記,則會導致重複連接)。

上面的查詢完美地工作。感謝所有。

+0

你在哪裏WHERE post_id = p.id,你的意思是WHERE p_id = p.id?我不得不推斷你的桌子的結構,所以我的猜測可能會關閉。另外,你不使用表格標籤 - 對嗎? – 2013-03-22 21:06:14

回答

2

好了 - 這將工作,它具有消除子查詢的額外的好處(當你獲得大量的記錄,可以減慢你的速度):

SELECT p1.id, p1.title, p1.content, 
    group_concat(p2.id) as 'P IDs', 
    group_concat(p2.title) as 'P titles' 
FROM posts as p1 
JOIN tagsmap as tm1 on tm1.p_id = p1.id 
JOIN tagsmap as tm2 on tm2.t_id = tm1.t_id and tm1.p_id <> tm2.p_id 
JOIN posts as p2 on p2.id = tm2.p_id 
WHERE p2.id <> p1.id 
GROUP BY p1.id 
ORDER BY p1.id desc limit 5; 

我們正在做什麼這裏是從第一版帖子中選擇你想要的內容,通過他們的post.id將它們加入到tagsmap中,通過標籤id自動加入tagsmap以獲取所有相關標籤,然後再回到其他帖子(p2)獲取這些相關標籤指向的帖子。

使用GROUP BY丟棄所有加入的學生,你就在那裏。

2

是什麼?

SELECT id, title, content 
     (SELECT GROUP_CONCAT(concat(cast(id as varchar(10)), ':', title)) FROM posts  -- Select title of related posts 
     WHERE id <> p.id AND id IN (     
      SELECT p_id FROM tagsmap     -- Select reletad post ids from tagsmap 
      WHERE t_id IN (
       SELECT t_id FROM tagsmap    -- Select the tags of the current post 
       WHERE post_id = p.id) 
      ) ORDER BY id DESC LIMIT 0, 3) as related 
FROM posts as p ORDER BY id DESC LIMIT 5