我有以下表格:一个项目可能有很多类别,一个类别可能有很多项目......
**project**
proj_id pk
proj_name
proj_descr
proj_what_we_did
proj_url
proj_descr_url
**project_per_categories**
project_proj_id pk
category_cat_id pk
**category**
cat_id pk
cat_name
以下选择:
SELECT proj_name, proj_descr,
proj_what_we_did, proj_url,
proj_descr_url, cat_name, foto_url
FROM project p, project_per_categories pc,
category c, foto f
WHERE p.proj_id = pc.project_proj_id AND
pc.category_cat_id = c.cat_id AND
p.proj_id = f.foto_id
ORDER BY p.proj_id DESC
LIMIT 6
在var_dump中带来以下结果:
array (size=2)
0 =>
array (size=7)
'proj_name' => string 'Rockable Magazine' (length=17)
'proj_descr' => string 'Id nihil consectetur facilis assumenda minimau'(length=329)
'proj_what_wi_did' => string 'Web Design' (length=10)
'proj_url' => string 'http://localhost/datacode/projeto' (length=33)
'proj_descr_url' => string 'Rockable-Magazine' (length=17)
'cat_name' => string 'web design' (length=10)
'foto_url' => string 'localhost/datacode/portfolio/case_study.jpg' (length=43)
1 =>
array (size=7)
'proj_name' => string 'Rockable Magazine' (length=17)
'proj_descr' => string 'Id nihil consectetur facilis assumenda minimau'(length=329)
'proj_what_we_did' => string 'Web Design' (length=10)
'proj_url' => string 'http://localhost/datacode/projeto' (length=33)
'proj_descr_url' => string 'Rockable-Magazine' (length=17)
'cat_name' => string 'css' (length=3)
'foto_url' => string 'localhost/datacode/portfolio/case_study.jpg' (length=43)
现在我会问,请注意,只有cat_name具有不同的值,那么我如何在用逗号分隔的cat_name字段中内爆或聚合这两个或多个值?
答案 0 :(得分:1)
查看group_concat函数。这样的事情对你有用:
SELECT
proj_name,
proj_descr,
proj_what_we_did,
proj_url,
proj_descr_url,
group_concat(cat_name),
foto_url
FROM project p,
project_per_categories pc,
category c,
foto f
WHERE p.proj_id = pc.project_proj_id
AND pc.category_cat_id = c.cat_id
AND p.proj_id = f.foto_id
GROUP BY p.proj_id
ORDER BY p.proj_id DESC
LIMIT 6