如何编写查询以将多个字符串聚合到一个字段中?

时间:2015-06-26 09:35:08

标签: mysql aggregate string

我正在尝试合并三个表。 第一个表有id和data_name, 第二个表data_id,option_id和property, 第三个表user_id,data_id。

例如:

first table
+----+-----------+
| id | data_name |
+----+-----------+
| 1  + veri1     |
| 2  + veri2     |
| 3  + veri3     |
+---++-----------+

second table 
+----------+----------+-----------+
data_id    | property | option_id |
+----------+----------+-----------+
| 1        | blue     | 1         |
| 1        | cold     | 2         |
| 2        | gray     | 1         |
| 2        | hot      | 2         |
| 3        | green    | 1         |
| 3        | cold     | 1         |
+----------+----------+-----------+

third table
+----------+-----------+
| user_id  | data_id   |
+----------+-----------+
| 1        | 2         |
| 2        | 3         |
| 3        | 1         |
+----------+-----------+

我想得到:

user: 1
data: veri2
properties: gray - hot

如何为此编写SQL?

2 个答案:

答案 0 :(得分:1)

此查询应该这样做。但是,property将以逗号分隔,而不是-

Select user_id,data_name, GROUP_CONCAT(property)
From Table1 INNER JOIN Table2 ON Table1.id = Table2.data_id
INNER JOIN Table3 ON Table1.id = Table3.data_id
GROUP BY Table1.id

答案 1 :(得分:1)

首先从FROM子句开始。您想要存储的数据在哪里?

FROM user_first_table
JOIN property_second_table
JOIN user_data_third_table

然后考虑你应该加入的条件(我发现重新排序表更容易)

FROM user_data_third_table t 
JOIN user_first_table f ON f.id = t.user_id
JOIN property_second_table s ON s.data_id = t.data_id

然后使用WHERE子句缩小范围,例如:只想要veri1的数据

FROM user_data_third_table t 
JOIN user_first_table f ON f.id = t.user_id
JOIN property_second_table s ON s.data_id = t.data_id
WHERE f.data_name = 'veri1'

然后标记您想要的数据字段

SELECT f.id as 'user', f.data_name as 'data', s.property as 'properties'
FROM user_data_third_table t 
JOIN user_first_table f ON f.id = t.user_id
JOIN property_second_table s ON s.data_id = t.data_id
WHERE f.data_name = 'veri1'