如何在MYSQL中选择多个行值作为列值?

时间:2014-05-09 12:53:10

标签: mysql sql

我有两个按ID链接的表格(下面的简化示例):

Table 1

ID     NAME
1      John
2      Frank

Table 2

ID     DAY     TIME_FROM    TIME_TO
1      Sun     8:00         15:00
1      Mon     8:00         15:00
1      Tue     NULL         NULL
1      Wed     NULL         NULL
1      Thu     NULL         NULL
1      Fri     8:00         15:00
1      Sat     8:00         15:00
2      Sun     8:00         15:00
...

我想要的是一个查询,理想地返回一个字段中每个ID的缩写天数,如下所示:

ID     NAME    DAYS 
1      John    S M F S 
2      Frank   S M T W T F S

或者也许:

ID     NAME    SUN    MON   TUE    
1      John    TRUE   TRUE  FALSE
2      Frank   TRUE   TRUE  TRUE

如果可能的话,首选解决方案。

2 个答案:

答案 0 :(得分:0)

使用GROUP_CONCAT()功能

SELECT t1.ID,t1.NAME,
       GROUP_CONCAT(`DAY` SEPERATOR ' ') as `DAYS`
FROM table1 t1
INNER JOIN table2 t2
ON t1.ID=t2.ID
GROUP BY t1.ID,t1.NAME

答案 1 :(得分:0)

试试这个:

  1. 首先解决方案:

    SELECT T1.ID,T1.Name,
            GROUP_CONCAT(T2.`DAY` SEPARATOR ' ') as Day
    FROM Table1 T1 JOIN
         Table2 T2 ON T1.Id=T2.Id
    GROUP BY T1.ID,T1.Name
    

    结果:

    ID  NAME    DAY
    1   John    Thu Fri Sat Sun Mon Tue Wed
    2   Frank   Sun
    

    注意:使用3个字母可避免SatSun之间的混淆。 查看SQL Fiddle中的结果。

  2. 第二个解决方案:

    SELECT T1.ID,T1.Name,
            MAX(CASE WHEN (COALESCE(TIME_FROM,TIME_TO) IS NOT NULL  AND `DAY` ='Sun') THEN 'TRUE' ELSE 'FALSE' END) as SUN,
            MAX(CASE WHEN (COALESCE(TIME_FROM,TIME_TO) IS NOT NULL  AND `DAY` ='Mon') THEN 'TRUE' ELSE 'FALSE' END) as MON,
            MAX(CASE WHEN (COALESCE(TIME_FROM,TIME_TO) IS NOT NULL  AND `DAY` ='Tue') THEN 'TRUE' ELSE 'FALSE' END) as TUE,
            MAX(CASE WHEN (COALESCE(TIME_FROM,TIME_TO) IS NOT NULL  AND `DAY` ='Wed') THEN 'TRUE' ELSE 'FALSE' END) as WED,
            MAX(CASE WHEN (COALESCE(TIME_FROM,TIME_TO) IS NOT NULL  AND `DAY` ='Thu') THEN 'TRUE' ELSE 'FALSE' END) as THU,
        MAX(CASE WHEN (COALESCE(TIME_FROM,TIME_TO) IS NOT NULL  AND `DAY` ='Fri') THEN 'TRUE' ELSE 'FALSE' END) as FRI,
        MAX(CASE WHEN (COALESCE(TIME_FROM,TIME_TO) IS NOT NULL  AND `DAY` ='Sat') THEN 'TRUE' ELSE 'FALSE' END) as SAT
    FROM Table1 T1 JOIN
         Table2 T2 ON T1.Id=T2.Id
    GROUP BY T1.ID,T1.Name
    

    <强>解释

    COALESCE将有助于检查TIME_FROMTIME_TO NULL

    结果(使用给定示例):

    ID  NAME    SUN     MON     TUE     WED     THU     FRI     SAT
    1   John    TRUE    TRUE    FALSE   FALSE   FALSE   TRUE    TRUE
    2   Frank   TRUE    FALSE   FALSE   FALSE   FALSE   FALSE   FALSE
    

    结果为SQL Fiddle