如何在MySql查询中减少结果集

时间:2012-02-21 00:47:39

标签: mysql

我正在运行下面的查询来创建两个表的交叉表:

SELECT vals.element_id AS order_id, 
IF( labs.label = "Gender", vals.value, 0 ) AS `Gender`, 
IF( labs.label = "Date of Birth", vals.value, 0 ) AS `Date of Birth`
FROM uc_extra_fields_values vals, uc_extra_fields labs
WHERE labs.field_id = vals.field_id
AND vals.element_id
IN ( 1022, 1023, 1024, 1074 )

这将返回以下结果:

order_id Gender DOB

1022    female  0
1022    0   4/02/2002
1022    0   0
1022    0   0
1022    0   0
1022    0   0
1023    female  0
1023    0   15/08/2002
1023    0   0
1023    0   0
1023    0   0
1023    0   0
1024    male    0
1024    0   17/11/1999
...

如何减少结果集,使其如下所示:

order_id Gender DOB

1022    female  4/02/2002
1023    female  15/08/2002
1024    male    17/11/1999

我尝试了一个' GROUP BY order_id'条款,但刚刚返回:

order_id Gender Date of Birth
1022    female  0
1023    female  0
1024    male    0
1074    male    0

2 个答案:

答案 0 :(得分:0)

这应该给你一个手

SELECT
    vals.element_id AS order_id,
    labs_gender.value AS `Gender`,
    labs_dob.value AS `Date of Birth`,

FROM uc_extra_fields_values AS vals

INNER JOIN uc_extra_fields AS labs_gender
ON labs_gender.field_id = vals.field_id
AND labs_gender.label = 'Gender'

INNER JOIN uc_extra_fields AS labs_dob
ON labs_dobs.field_id = vals.field_id
AND labs_dob.label = 'Date of Birth'

WHERE vals.element_id IN ( 1022, 1023, 1024, 1074 )

作为一个注释,如果每行val都精确地具有1个DoB并且恰好是1个性别,那么以一种反映即简单表格的方式进行结构将更加明智

出于性能原因,可能有必要在uc_extra_fields上设置一个带有列(field_id,label)的键,因为它有助于连接

答案 1 :(得分:0)

最后,我使用以下查询返回正确的结果:

SELECT order_id, 
GROUP_CONCAT(CASE field_id WHEN 1 THEN value END) AS gender,
GROUP_CONCAT(CASE field_id WHEN 2 THEN value END) AS dob
FROM
(SELECT 
    vals.element_id AS order_id,
    vals.value,
    labs.label,
    labs.field_id
FROM uc_extra_fields_values vals, uc_extra_fields labs
WHERE labs.field_id = vals.field_id
AND vals.element_id IN ( 1022, 1023, 1024, 1074 )) AS ex_fields
GROUP BY order_id

内部查询返回:

1022    female          Gender                      1
1022    04/02/2002      Date of Birth               2

外部查询将表格转向返回:

order_id    gender  dob
1022        female  04/02/2002
1023        female  15/08/2002
1024        male    17/11/1999
1074        male    27/08/1973