我需要编写一个 SQL 查询来合并两个表...
Table: names
+-------------+---------------+
| id | Name |
+-------------+---------------+
| 1 | Bob |
| 2 | Geoff |
| 3 | Jim |
+-------------+---------------+
Table: attributes
+-------------+---------------+
| id | Attribute |
+-------------+---------------+
| 1 | Age |
| 2 | Height |
| 3 | Weight |
+-------------+---------------+
...以便 names 表中的每条记录都具有 Attributes 表中每条记录的副本。
即
+-------------+---------------+---------------+
| id | Name | Attribute |
+-------------+---------------+---------------+
| 1 | Bob | Age |
| 2 | Bob | Height |
| 3 | Bob | Weight |
| 4 | Geoff | Age |
| 5 | Geoff | Height |
| 6 | Geoff | Weight |
| 7 | Jim | Age |
| 8 | Jim | Height |
| 9 | Jim | Weight |
+-------------+---------------+---------------+
有办法吗?
最佳答案
SELECT n.name, a.attribute from names n cross join attributes a
同样可以通过以下查询实现:
SELECT n.name, a.attribute from names n join attributes a ON 1=1
唯一的问题是您在输出中显示了从 1 到 9 的 ID,但示例数据中没有这样的 ID。但是,如果您的表具有自动增量功能,那么在您插入此数据后,ID 将如您所愿。
更新:
如评论中所建议,如果您需要 id,则可以执行以下操作:
SELECT (n.id-1)*3+a.id AS id, n.name, a.attribute from names n cross join attributes a
关于mysql - 我如何在 SQL 中组合这两个表,以便第一个表的每一行都有第二个表中每一行的副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29275341/