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

标签 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?

最佳答案

首先从 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'

关于mysql - 如何编写查询以将多个字符串聚合到一个字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31076633/

相关文章:

php - 按国家 ip 范围阻止用户注册

mysql - 我怎样才能找到一个列是否在 mysql 中是 auto_increment?

php - 如何在php mysql中访问复选框的值

java - 尝试更新 mysql 驱动程序以摆脱 java.sql.SQLFeatureNotSupportedException

R计算每年超标的天数

python - 如何更改列表中元素的位置

java - 尝试在字符串数组中查找字符串元素

sql - 计算与组内最小值的差值

variables - 有没有办法将总和传递给包级变量?

arrays - 如何组合匹配模式的数组中的元素?