PHP MYSQL查询结合并添加两个平衡结果

时间:2013-01-29 09:56:20

标签: php mysql

有人请帮我解决我的sql查询我已经花了两天时间......

我有一个下面给出的MYSQL查询

(SELECT
  c.cl_list as cl_list,
  c.name as name,
  pc.value as value,
  count( pc.value) as total
FROM
  projs p 
  LEFT JOIN classify_proj_new pc 
    ON p.proj_id = pc.proj_id_fk
  LEFT JOIN classify_list c 
    ON c.cl_list = pc.class_id_fk
WHERE
  MATCH ( p.title ) AGAINST ( 'jerm'  IN BOOLEAN MODE )
GROUP BY 
  c.cl_list,
  pc.value)
UNION ALL
(SELECT
  c.cl_list as cl_list,
  c.name as name,
  pc.value as value,
  count( pc.value) as total
FROM
  jerm p 
  LEFT JOIN classify_jerm_new pc
    ON p.jerm_id = pc.jerm_id_fk
  LEFT JOIN classify_list c
    ON c.cl_list = pc.class_id_fk
WHERE
  MATCH ( p.jermname ) AGAINST ( 'jerm'  IN BOOLEAN MODE )
GROUP BY
  c.cl_list,
  pc.value)

给出了(下面)的结果:

  cl_list      name              value        total
------------------------------------------------------------------------------------
    1       department         jewller          2
    3       price                 50            2
    6       color                blue           1
    6       color                Red            2
    1       department         jewller          1
    6       color                Red            1

但我试图得到一个结果,可以添加重复值的总和,避免重复值......有些事情如下(下图):

  cl_list      name              value        total
------------------------------------------------------------------------------------
    1       department         jewller          3
    3       price                 50            2
    6       color                blue           1
    6       color                Red            3
有人请帮助我,我对自己的输出感到非常难过......

非常感谢你提前...

3 个答案:

答案 0 :(得分:3)

通过cl_list,名称和值从您的查询和组中进行选择:

SELECT
  cl_list,
  name,
  value,
  sum(total) as total
FROM (
  -- your current query here ...
) data
GROUP BY
  cl_list,
  name,
  value

答案 1 :(得分:1)

尝试以下代码。它将显示独特的记录并避免重复。

GROUP BY c.name

答案 2 :(得分:0)

group名称和值的结果

(SELECT c.cl_list as cl_list, c.name as name, pc.value as value, count( pc.value) as total
FROM projs p 
LEFT JOIN classify_proj_new pc ON p.proj_id = pc.proj_id_fk
LEFT JOIN classify_list c ON c.cl_list = pc.class_id_fk
WHERE MATCH ( p.title ) AGAINST ( 'jerm'  IN BOOLEAN MODE )
GROUP BY c.name, pc.value)
UNION ALL
(SELECT  c.cl_list as cl_list, c.name as name, pc.value as value, count( pc.value) as total
 FROM jerm p 
 LEFT JOIN classify_jerm_new pc ON p.jerm_id = pc.jerm_id_fk
 LEFT JOIN classify_list c ON c.cl_list = pc.class_id_fk
 WHERE MATCH ( p.jermname ) AGAINST ( 'jerm'  IN BOOLEAN MODE )
 GROUP BY c.name, pc.value)