2013-04-30 103 views
1

日期表:MySQL查詢Concat的2行同一列

id start_date end_date 
1 2013-04-28 2013-04-29 
3 2013-04-18 2013-04-25 
4 2013-05-22 2013-04-30 
5 2013-05-02 2013-04-30 
6 2013-04-29 2013-04-30 

時間表:

id start_time end_time 
1 11:00 AM 12:00 AM 
2 12:00 PM 03:00 PM 

APP表:

id app_name 
1 Test 
2 Test1 

表的關係是店相關表格:

app_id date_id time_id 
1   1  1 
1   1  2 
2   1  2 

我解僱一個SQL查詢,從數據庫中獲取的數據:

SELECT app.id as id,app.app_name,date.id as date_id , 
       date.start_date,date.end_date,time.id as time_id,time.start_time,time.end_time as end_time 
       FROM related_data 
       INNER JOIN app ON app.id = app_id 
       INNER JOIN DATE ON date.id = date_id 
       INNER JOIN Time ON time.id = time_id 
       LIMIT 0 , 30 

但它返回:

id app_name date_id  start_date end_date time_id  start_time end_time 
1 Test 1 2013-04-28 2013-04-29 1 11:00 AM 12:00 AM 
1 Test 1 2013-04-28 2013-04-29 2 12:00 PM 03:00 PM 
2 Test1 1 2013-04-28 2013-04-29 2 12:00 PM 03:00 PM 

,但我想是這樣的:

id app_name date_id  start_date end_date time_id  start_time end_time 
1 Test 1 2013-04-28 2013-04-29 1,2  11:00 AM,12:00PM 12:00 AM,03:00PM 
2 Test1 1 2013-04-28 2013-04-29 2 12:00 PM 03:00 PM 

如果應用程序ID是相同和日期id或時間id不同然後concat數據。

回答

1

使用GROUP_CONCAT

SELECT app.id as id, 
     app.app_name, 
     date.id as date_id , 
     date.start_date, 
     date.end_date, 
     GROUP_CONCAT(time.id) as time_id, 
     GROUP_CONCAT(time.start_time) start_time, 
     GROUP_CONCAT(time.end_time) as end_time 
FROM related_data 
     INNER JOIN app 
      ON app.id = app_id 
     INNER JOIN DATE 
      ON date.id = date_id 
     INNER JOIN Time 
      ON time.id = time_id 
GROUP BY app.id as id, 
      app.app_name, 
      date.id as date_id , 
      date.start_date, 
      date.end_date 
LIMIT 0, 30 
+0

謝謝...真是太棒了...! – John 2013-04-30 05:58:35

+0

不客氣':D' – 2013-04-30 06:01:10

+0

我們可以將start_time&end_time與單列連接起來嗎? – John 2013-04-30 07:39:07