2013-02-08 53 views
2

我有三個表MySQL的加入對單個資源ID 3個表

  • resources_connection
    1. RESOURCE_ID
    2. resource_tag_id
  • resources_flags
    1. USER_ID
    2. RESOURCE_ID
  • resources_votes
    1. USER_ID
    2. RESOURCE_ID

每個是一個2列的表,INT(11),用於既設計成允許我查詢的標籤的數量,標誌和投票基於單個'資源ID'

我目前使用此查詢嘗試和ge標籤TA計數(resources_connection),旗(resources_flags)和投票(resources_votes):

SELECT COUNT(DISTINCT t1.resource_id) as votes, 
     COUNT(DISTINCT t2.resource_id) as flags, 
     COUNT(DISTINCT t3.resource_tag_id) as tags 
FROM ecruit_demo.resources_votes t1 
LEFT JOIN ecruit_demo.resources_flags t2 
    ON (t1.resource_id = t2.resource_id) 
JOIN ecruit_demo.resources_connection t3 
    ON (t1.resource_id = t3.resource_id) WHERE t1.resource_id = 4 

的問題是,該查詢返回正確的結果resource_id = 1但是當我設置resource_id到(針對其存在一個標籤)它返回全零。什麼是適當的查詢結構,以確保此查詢始終返回給定resource_id的標籤,標誌和投票的正確數量?

我還要補充一點,唯一的地方RESOURCE_ID = 4發生在數據庫處於resources_connection,其他兩個表沒有這個值

+0

感謝@Back在Flash編輯查詢的格式,使之可讀 –

+0

下列哪個是主表? –

+0

沒有真正的主表。這些表格旨在保存與包含ID,名稱,說明和網址的「資源」對象相關的值。爲了這個問題的目的,將有許多用戶來自每個資源對象的投票,標誌和標籤。 –

回答

3
SELECT resource_ID, 
     MAX(CASE WHEN types = 'votes' THEN totals ELSE NULL END) votes, 
     MAX(CASE WHEN types = 'flags' THEN totals ELSE NULL END) flags, 
     MAX(CASE WHEN types = 'tags' THEN totals ELSE NULL END) tags 
FROM  
    (
     SELECT resource_ID, 'votes' types, 
       COUNT(DISTINCT resource_ID) totals 
     FROM resources_votes 
     GROUP BY resource_ID 
     UNION 
     SELECT resource_ID, 'flags' types, 
       COUNT(DISTINCT resource_ID) totals 
     FROM resources_flags 
     GROUP BY resource_ID 
     UNION 
     SELECT resource_ID, 'tags' types, 
       COUNT(DISTINCT resource_tag_id) totals 
     FROM resources_connection 
     GROUP BY resource_ID 
    ) s 
-- WHERE resource_ID = 1 
GROUP BY resource_ID 
+0

返回'#1248 - 每個派生表都必須有自己的別名' –

+0

你有'''子查詢後? –

+0

出於某種原因,我認爲這是一個錯字。這工作完美。謝謝! –

0

我不是在MySQL確實不錯,但也許你可以試試:

將JOIN改爲LEFT JOIN,這樣查詢就會是這樣。

SELECT COUNT(DISTINCT t1.resource_id) as votes, 
      COUNT(DISTINCT t2.resource_id) as flags, 
      COUNT(DISTINCT t3.resource_tag_id) as tags 
    FROM ecruit_demo.resources_votes t1 
    LEFT JOIN ecruit_demo.resources_flags t2 
     ON (t1.resource_id = t2.resource_id) 
    LEFT JOIN ecruit_demo.resources_connection t3 
     ON (t1.resource_id = t3.resource_id) WHERE t1.resource_id = 4 
+0

返回與原始查詢相同的所有零:-( –