我正在使用一个拥有'Staff'列的MySQL数据库。例如:
ID BUSINESS STAFF
1 Business 1 Bob
2 Business 2 Bill
3 Business 3 Paul, Bill
4 Business 4 Bob
我的目标是使用Google Charts API创建一个饼图,显示每位员工有多少家企业,而且我在计算总金额方面遇到了麻烦。
图表使用格式:
var data = google.visualization.arrayToDataTable([
['Staff', 'Business'],
['Bob', 2],
['Bill', 2],
['Paul', 1]
]);
我如何回应这些线的数量?我花了40分钟搞砸了COUNT个查询,绝对没有快乐。
答案 0 :(得分:1)
我根据您的问题开发此代码,您应该根据您的表和字段更改服务器配置服务器名称,用户,密码,数据库
$server="server";
$user="user";
$password="password";
$database="database";
$cid=mysql_connect($server,$user,$password);
mysql_select_db($database,$cid);
$query="select * from table";
$rs=mysql_query($query,$conn);
$val=0;
while($row=mysql_fetch_array($rs))
{
$data=$row['business'];
$val=$val+trim(str_replace("Business","", "$data"));
}
$total=$val;
我使用了这段代码,我找到了总数;
答案 1 :(得分:1)
此处的评论中有一个共同主题,即normalization。通常,将多个值表示为单个列中的逗号分隔列表是一件坏事。
以下是备用数据库设计的一个工作示例,它可以帮助您朝着正确的方向前进:
create table staff
(
id int unsigned not null primary key auto_increment,
staffName varchar(250),
unique key `staffUIdx1` (staffName)
) ENGINE=InnoDB;
create table business
(
id int unsigned not null primary key auto_increment,
businessName varchar(250),
unique key `staffUIdx1` (businessName)
) ENGINE=InnoDB;
CREATE TABLE staffBusiness
(
id int unsigned not null primary key auto_increment,
staffId int unsigned not null,
businessId int unsigned not null,
unique key `staffBusinessUIdx1` (staffId,businessId),
CONSTRAINT `fk_staffBusiness_staff1` FOREIGN KEY (`staffId`) REFERENCES `staff` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_staffBusiness_business1` FOREIGN KEY (`businessId`) REFERENCES `business` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB;
insert into staff (staffName) values ('Bob');
insert into staff (staffName) values ('Bill');
insert into staff (staffName) values ('Paul');
insert into staff (staffName) values ('George');
insert into business (businessName) values ('Business 1');
insert into business (businessName) values ('Business 2');
insert into business (businessName) values ('Business 3');
insert into business (businessName) values ('Business 4');
insert into staffBusiness (staffId,businessId)
select s.id,b.id from staff s join business b
where s.staffName = 'Bob' and b.businessName in ('Business 1','Business 4');
insert into staffBusiness (staffId,businessId)
select s.id,b.id from staff s join business b
where s.staffName = 'Bill' and b.businessName in ('Business 2','Business 3');
insert into staffBusiness (staffId,businessId)
select s.id,b.id from staff s join business b
where s.staffName = 'Paul' and b.businessName in ('Business 3');
...然后查询将如下所示:
select staffName as Staff,count(sb.id) as Business
from staff s
left outer join staffBusiness sb on s.id = sb.staffId
group by staffName;
我已经包括了一名名为“乔治”的第四名员工,表明规范化的方法可以让您的员工也没有业务。