我正在尝试合并三个表。 第一个表有 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/