2012-09-14 54 views
1

首先祝賀這樣一個偉大的網站,它總是以最專業的答案彈出搜索。熱門報告指標MYSQL

我避過與MySQL連接和實際嘗試應用MySql上一些預先的過程,讓我們切入正題:

鑑於這些3個表:

CREATE TABLE `reports_indicators` (
    `report_id` int(11) NOT NULL, 
    `indicator_id` int(11) NOT NULL, 
    `reported` varchar(10) DEFAULT NULL, 
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    PRIMARY KEY (`id`,`report_id`,`indicator_id`), 
    KEY `fk_reports_has_indicators_indicators1` (`indicator_id`), 
    KEY `fk_reports_has_indicators_reports1` (`report_id`) 
) ENGINE=InnoDB AUTO_INCREMENT=77409 DEFAULT CHARSET=latin1; 

CREATE TABLE `reports` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `title` varchar(255) DEFAULT 'untiteled' 
) ENGINE=InnoDB AUTO_INCREMENT=11609 DEFAULT CHARSET=latin1; 
/*!40101 SET character_set_client = @saved_cs_client */; 

CREATE TABLE `indicators` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `name` varchar(100) DEFAULT NULL, 
    `description` text, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=312 DEFAULT CHARSET=latin1; 
/*!40101 SET character_set_client = @saved_cs_client */; 

我試圖讓最高報告指標,簡單...但我不能!

所有我能得到來自一個單一的報告一組指標:

SELECT * 
    FROM reports_indicators as ri 
    INNER JOIN indicators as i 
    ON i.id = ri.indicator_id 
    WHERE ri.report_id=6867 
    ORDER BY ri.report_id asc; 

我知道甚至沒有接近,但是當我開始嘗試AVG發現,可能不適合它的賴特地方。

任何幫助?

非常感謝!

bto。

+0

什麼是「*頂部報道指示燈* 「? – eggyal

+1

您'WHERE'子句僅指定一個報告ID,因此您只會獲取與該報告ID相關的數據。 –

+0

請更具體地查詢查詢的預期結果。顯示它必須返回的列的示例和示例值。 – Diego

回答

3

這是假定的「頂部報道指示器」,你的意思是有在reports_indicators表中的最相關記錄的指標將被分揀到先出現:

SELECT 
    i.id, 
    i.name, 
    COUNT(*) AS TotalReported 
FROM 
    reports_indicators as ri 
    INNER JOIN indicators as i 
     ON i.id = ri.indicator_id 
GROUP BY i.id, i.name 
ORDER BY COUNT(*) DESC; 
+0

@eggyal嗯,你是對的,那不可能。我會將其更改爲「COUNT()」,希望這是「最高報告指標」的意思,直到OP給出澄清。 –

+0

刪除了我的並投票了這一點,因爲我從「SUM」變爲「COUNT」後我的記錄變得重複了。 –

+0

您還可以添加限制條款以獲取您實際需要的數字。 –