你的数据库设计得很糟糕,你将会遇到很多麻烦。
使用当前结构,您可以使用以下命令获取计数find_in_set
函数,但你应该避免。
你的桌子是这样的
create table test
(jobid int ,city varchar(100));
insert into test values
(1,'New York'),
(2,'New York, Ohio,Virginia'),
(3,'New York,Virginia');
现在要获取计数,您可以使用以下命令
select
count(*) as tot from test
where
find_in_set('Virginia',city) > 0;
正如我提到的,这是一个糟糕的数据库设计,理想的情况是
- 首先是包含工作详细信息的工作表
- 包含所有位置的位置表
- 最后是链接工作和位置的表格
所以它看起来像
create table jobs (jobid int, name varchar(100));
insert into jobs values
(1,'PHP'),(2,'Mysql'),(3,'Oracle');
create table locations (id int, name varchar(100));
insert into locations values (1,'New York'),(2,'Ohio'),(3,'Virginia');
create table job_locations (id int, jobid int, location_id int);
insert into job_locations values
(1,1,1),(2,2,1),(3,2,2),(4,2,3),(5,3,1),(6,3,3);
现在获取计数和更多操作将相当容易
select
count(j.jobid) as tot
from jobs j
join job_locations jl on jl.jobid = j.jobid
join locations l on l.id = jl.location_id
where
l.name = 'Virginia'
要计算每个城市的所有工作并使用上述模式,这将非常简单
select
l.name,
count(j.jobid) as tot
from jobs j
join job_locations jl on jl.jobid = j.jobid
join locations l on l.id = jl.location_id
group by l.name
DEMO http://www.sqlfiddle.com/#!2/10d51/2