2011-02-28 42 views
0

我有一個基於鏈接表的共享標籤和發言者數量來排列項目的聲明,但是我希望它也能夠從實際上不在查詢中的主要tbl_talks中提取talk_title和talk_brief信息現在(只使用鏈接表)。 基本上,鏈接表具有talk_id和tag_id或talk_id和speaker_id。如何將聯接添加到此龐大的SQL聯合語句中?

我嘗試了幾種嘗試左連接的方法,或者在聯合應用到配對的SELECT中添加tbl_talks,但沒有運氣。我需要兩個tbl_linking_talk_tag.talk_id和tbl_linking_speakers_talk與tbl_talks.talk_id並與,搶talk_title和talk_brief從tbl_talks

SELECT talk_id, count(*) AS common_term_count FROM 
     (
     SELECT talk_id FROM tbl_linking_talk_tag WHERE tag_id IN 
     (SELECT tag_id FROM tbl_linking_talk_tag WHERE talk_id = 1) 
     UNION ALL 
     SELECT talk_id FROM tbl_linking_speakers_talk WHERE speaker_id IN 
     (SELECT speaker_id FROM tbl_linking_speakers_talk WHERE talk_id = 1) 
     ) AS accumulator_table 

WHERE talk_id != 1 

GROUP BY talk_id 

ORDER BY common_term_count DESC 

回答

0

我得到了它,此代碼的工作:

SELECT a.talk_id, a.talk_image, a.talk_title, a.talk_brief, count(b.talk_id) AS common_term_count 
     FROM tbl_talks a LEFT OUTER JOIN 
      (
      SELECT talk_id FROM tbl_linking_talk_tag WHERE tag_id IN 
       (SELECT tag_id FROM tbl_linking_talk_tag WHERE talk_id = 1) 
      UNION ALL 
      SELECT talk_id FROM tbl_linking_speakers_talk WHERE speaker_id IN 
       (SELECT speaker_id FROM tbl_linking_speakers_talk WHERE talk_id = 1) 
      ) AS b 
      ON a.talk_id = b.talk_id  
     WHERE a.talk_id != 1   
     GROUP BY b.talk_id  
     ORDER BY common_term_count DESC 
1

關聯不要認爲你需要工會在這種情況下。如果你需要的是再算上爲什麼不嘗試像..

SELECT talk_id, (SELECT COUNT(*)FROM tbl_linking_talk_tag Sub其中TAG_ID IN (SELECT TAG_ID FROM tbl_linking_talk_tag WHERE talk_id = 1)和maintalk.talk_id = sub.talk_id)+ (SELECT COUNT(*)FROM tbl_linking_speakers_talk SUB1 WHERE speaker_id IN (SELECT speaker_id FROM tbl_linking_speakers_talk WHERE talk_id = 1),並和maintalk.talk_id = sub1.talk_id ),talk_title,talk_brief 從maintalk 其中talk_id != 1 group by talk_id

synta X可能需要一些固定,但方法是

選擇列,從maintable