如何分组现场数据?

时间:2013-05-03 02:58:23

标签: mysql

我有sql查询来显示数据

"SELECT
  `artikel`.`foto_naam`,
  `fotografer`.`id`,
  `fotografer`.`name_fotografer`,
  `customer`.`first_name`,
  `customer`.`last_name`,
  `fotografer`.`domain_name`,
  `fotografer`.`email`,
  `order`.`invoice_no`,
  `order`.`order_cost`,
  `order`.`total_cost`,
  `order`.`invoice_date`,
  `order`.`payment`,
  `order`.`status`
FROM
  `artikel_group`
  INNER JOIN `artikel` ON `artikel`.`artikelgroup_id` = `artikel_group`.`id`
  INNER JOIN `fotografer` ON `artikel_group`.`fotografer_id` = `fotografer`.`id`
  INNER JOIN `order_has_artikelgroup` ON `order_has_artikelgroup`.`artikelgroup_id` = `artikel_group`.`id`
  INNER JOIN `order` ON `order`.`id` = `order_has_artikelgroup`.`order_id` 
  INNER JOIN `customer` ON `order`.`customer_id` = `customer`.`id`"

我的st查询在btowser中的查询结果我使用php framework codeigniter

Name  | email           | customer | invoice id| 
Lekto | lekto@gmail.com | edwin    | 11        |
Lekto | lekto@gmail.com | risa     | 12        |
Lekto | lekto@gmail.com | edwin    | 13        |
heko  | heko@gmail.com  | pae      | 15        |
heko  | heko@gmail.com  | edwin    | 16        |

如何分组字段

Name  | email           | customer | invoice id|
Lekto | lekto@gmail.com | edwin    | 11        |
      |                 | risa     | 12        |
      |                 | edwin    | 13        |
heko  | heko@gmail.com  | pae      | 15        |
      |                 | edwin    | 16        |

请帮助显示这样的查询

2 个答案:

答案 0 :(得分:1)

奇怪的问题,但是如果你真的需要在MySQL中,那么你可以使用USER VARIABLES为列表中的子项设置Nameemail列为''(空字符串)。

DEMO FIDDLE 或者例如

select 
    if(@tName!= Name, if(@'tNAME':= Name, Name,Name) , '' ),
    if(@tEmail!= Email, if(@'tEmail':= Email, Email ,Email) , '' ),
    customer,
    invoice_id,
    /* blah blah blah */
from 
    tables
    join (select @'tName':='', @'tEmail':='') T on 1=1 
/* blah blah blah */

我提供join (select @'tName':='') T on 1=1来重新初始化用户变量,万一你无法控制它们。

答案 1 :(得分:0)

你可以在mysql中做的一件事就是用group bygroup_concat()包装你的查询。像这样:

SELECT
    name, 
    email, 
    group_concat(customer) AS customers, 
    group_concat(invoice_id) AS invoice_ids
FROM
    (...query you already have..)
GROUP BY
    name, email

结果将如下所示:

name    email               customers           invoice_ids

heko    heko@gmail.com      pae,edwin           15,16
Lekto   lekto@gmail.com     edwin,risa,edwin    11,12,13

PLZ SEE FIDDLE