gpt4 book ai didi

php - 根据字段对数据进行分组并在 PHP 中提取不同的值

转载 作者:行者123 更新时间:2023-11-29 05:23:53 25 4
gpt4 key购买 nike

我有一个包含 5 个字段的数据库:

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

最佳答案

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

你必须使用 sum,而不是 count,因为其中的 opinion = whatever 返回 true 或 false(1 或 0)。

更新:

好吧,我的查询非常有效: 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

关于php - 根据字段对数据进行分组并在 PHP 中提取不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22500486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com