mysql:从连接返回多个csv列

时间:2013-03-20 21:12:27

标签: mysql database group-concat

我有这个问题:

SELECT * 
FROM  `test` t
LEFT JOIN  `result` r ON r.test_id = t.id
LEFT JOIN  `parameter` p ON p.test_id = t.id

返回:

id                name   id test_id      description    id test_id          name
 1 test w/o parameters    1       1 the first result  NULL    NULL          NULL
 1 test w/o parameters    2       1 the second result NULL    NULL          NULL
 2 test w/ paramters   NULL    NULL              NULL    1       2  command_line
 2 test w/ paramters   NULL    NULL              NULL    2       2        userid

我想要的是:

id                name                             results           parameters
 1 test w/o parameters  the first result,the second result                 NULL
 2 test w/ paramters                                  NULL  command_line,userid

我试图让GROUP_CONCAT工作,但NULLS被丢弃了。有没有办法说服GROUP_CONCAT返回空值?

我真正想拥有的是这样的,但这都是错的:

SELECT * , group_concat(r.description), group_concat(p.name)
  FROM `test` t 
  left join `result` r on r.test_id = t.id
  left join `parameter` p on p.test_id = t.id

这将返回非NULL行:

SELECT * , group_concat(r.description)
  FROM `test` t 
  LEFT JOIN `result` r on r.test_id = t.id
  LEFT JOIN `parameter` p on p.test_id = t.id

1 个答案:

答案 0 :(得分:1)

在子查询中首先将值连接在一起可能会更容易,然后将它们连接到父表(DEMO)中:

SELECT t.id, t.name, r.results, p.parameters
FROM  `test` t
LEFT JOIN  (select test_id, group_concat(result) results
            from `result` r group by test_id) r ON r.test_id = t.id
LEFT JOIN  (select test_id, group_concat(name) parameters
            from `parameter` p group by test_id) p ON p.test_id = t.id;

结果:

| ID |                NAME |                            RESULTS |          PARAMETERS |
---------------------------------------------------------------------------------------
|  1 | test w/o parameters | the first result,the second result |              (null) |
|  2 |   test w/ paramters |                             (null) | command_line,userid |