2014-03-19 53 views
1

不同的價值觀我有5場數據庫:組數據基於字段並提取PHP

1. id 
2. text (just a phrase in each row) 
3. opinion (holds values: positive or negative or neutral) 
4. location (where the person who wrote the text was) 
5. label (specific to the text) 

我想要做的就是使用PHP & MySQL的獲取特定標籤的位置和能夠顯示出這個位置有多少積極消極中立的意見。

結果應該最終是這樣的:

Amsterdam - 2 positive, 3 negative, 5 neutral 
.... - #.., #.., #.. 
and so on.. 

我要繪製的條形圖這些數據,這就是爲什麼我需要它。我想過使用GROUP BY,但出於某種原因,我無法得到我想要的結果。

我該怎麼做?

編輯: 樣品上 sqlfiddle

期望的結果:

Location | Positive | Negative | Neutral 
city1    2    1    2 
city2    2    1    0 

回答

3
select 
location, 
sum(opinion > 0) as positive, 
sum(opinion < 0) as negative, 
sum(opinion = 0) as neutral 
from 
your_table 
where label = 'whatever' 
group by location 

你必須使用金額,不計,因爲在它的opinion = whatever返回true或false(1或0 )。

UPDATE:

好了,我的查詢工作完美:sqlfiddle

當然,你必須把它調整到你的表和數據:

select 
location, 
sum(opinion = 'Positive') as positive, 
sum(opinion = 'Negative') as negative, 
sum(opinion = 'Neutral') as neutral 
from 
results 
where label = 'label1' 
group by location 
+0

使用此查詢,它看起來像我到達那裏,但結果顯示,一切都是中性的。例如,一個地點有31箇中立,6個積極,1個否定,並且只有38箇中立。 這是爲什麼? – Andrew

+0

然後這個問題必須缺乏一些信息。請提供樣本數據和期望的結果,最好在http://sqlfiddle.com上哦,並且'show create table your_table_name_here'的結果,可以肯定。 – fancyPants

+0

編輯我的第一篇文章,添加sqlfiddle樣本數據。 – Andrew

0

我給這基於假定值進行查詢。

SELECT count(id) 
    FROM table_name 
WHERE opinion="positive" and location="Chennai" and label="php" 

此查詢將給出給定條件的總數。當您在php中使用它時,它可以更改爲動態。

+0

我實際上想按地點進行分組,並且不會將意見作爲輸入,而是針對每個地點獲取意見。 – Andrew

+0

@Andrew:你能提供你要爲這個查詢提供什麼樣的輸入,這樣就可以根據你的需求輕鬆地構建查詢。 – Rajesh

+0

編輯我的初始帖子,底部。 – Andrew