MySql查询连接同一列的2行
Posted
技术标签:
【中文标题】MySql查询连接同一列的2行【英文标题】:MySql query to concat 2 rows of the same column 【发布时间】:2013-04-23 23:13:30 【问题描述】:日期表:
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
应用表:
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 不同,则连接数据。
【问题讨论】:
【参考方案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
mysql GROUP_CONCAT()
【讨论】:
我们可以将 start_time 和 end_time 连接在一个列中吗? 试试,CONCAT(start_date, ' to ', end_date)
我能做到吗..如果time_id不一样则连接日期否则只有一个数据..?
添加DISTINCT
示例,GROUP_CONCAT(DISTINCT time.id)
以上是关于MySql查询连接同一列的2行的主要内容,如果未能解决你的问题,请参考以下文章