[英]MYSQL: inserting data from other tables
I'm trying to insert data from two other tables. 我正在尝试从其他两个表插入数据。 I currently have two tables, t1 and t2: 我目前有两个表,t1和t2:
t1: T1:
col1 col2 col3 col4 col5
A A B A C
B B C C A
B C B B A
C A A A B
and t2: 和t2:
A B C
col1 4 99 81
col2 50 26 38
col3 36 38 11
col4 16 49 70
col5 42 83 93
My goal is to form a new table which would simply use data from t1 and t2 and form a new table such as: 我的目标是形成一个新表,该表将仅使用t1和t2中的数据,并形成一个新表,例如:
col1 col2 col3 col4 col5
4 50 38 16 93
99 26 11 70 42
99 38 38 49 42
81 50 36 16 83
I have been using CASE-function, but I've faced problems with attaching the tables. 我一直在使用CASE函数,但是在附加表时遇到了问题。 Any advices? 有什么建议吗?
Thanks! 谢谢!
If we convert t2
from a wide table to a long table: 如果将t2
从宽表转换为长表:
mysql> CREATE VIEW tidyt2 AS
SELECT x as 'col', 'A' as 'label', A 'value' FROM t2
UNION SELECT x as 'col', 'B' as 'label', B 'value' FROM t2
UNION SELECT x as 'col', 'C' as 'label', C 'value' FROM t2;
Query OK, 0 rows affected (0.03 sec)
mysql> select * from tidyt2;
+------+-------+-------+
| col | label | value |
+------+-------+-------+
| col1 | A | 4 |
| col2 | A | 50 |
| col3 | A | 36 |
| col4 | A | 16 |
| col5 | A | 42 |
| col1 | B | 99 |
| col2 | B | 26 |
| col3 | B | 38 |
| col4 | B | 49 |
| col5 | B | 83 |
| col1 | C | 81 |
| col2 | C | 38 |
| col3 | C | 11 |
| col4 | C | 70 |
| col5 | C | 93 |
+------+-------+-------+
15 rows in set (0.00 sec)
Then the desired table can be expressed using left joins: 然后可以使用左连接来表达所需的表:
mysql> SELECT t21.value as 'col1'
, t22.value as 'col2'
, t23.value as 'col3'
, t24.value as 'col4'
, t25.value as 'col5'
FROM t1
LEFT JOIN tidyt2 as t21 ON t1.col1 = t21.label AND t21.col='col1'
LEFT JOIN tidyt2 as t22 ON t1.col2 = t22.label AND t22.col='col2'
LEFT JOIN tidyt2 as t23 ON t1.col3 = t23.label AND t23.col='col3'
LEFT JOIN tidyt2 as t24 ON t1.col4 = t24.label AND t24.col='col4'
LEFT JOIN tidyt2 as t25 ON t1.col5 = t25.label AND t25.col='col5';
+------+------+------+------+------+
| col1 | col2 | col3 | col4 | col5 |
+------+------+------+------+------+
| 4 | 50 | 38 | 16 | 93 |
| 99 | 26 | 11 | 70 | 42 |
| 99 | 38 | 38 | 49 | 42 |
| 81 | 50 | 36 | 16 | 83 |
+------+------+------+------+------+
4 rows in set (0.00 sec)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.