mysql 动态行
我想用动态行在 MySQL 上执行查询。
想象一下:
表phones_categories
+----+------------+
| id | name |
+----+------------+
| 1 | Home Phone |
| 2 | Cell Phone |
| 3 | Fax |
+----+------------+
表phones
+----+-----------+-------------------+--------------+
| id | entity_id | phone_category_id | phone_number |
+----+-----------+-------------------+--------------+
| 1 | 1 | 1 | X19 XXX 2XX |
| 2 | 1 | 3 | X19 XXX 2XX |
| 3 | 2 | 1 | X18 XXX 4XX |
| 4 | 2 | 3 | X18 XXX 4XX |
+----+-----------+-------------------+--------------+
我希望有以下输出:
+-----------+--------------+--------------+-------------+
| entity_id | Home Phone | Cell Phone | Fax |
+-----------+--------------+--------------+-------------+
| 1 | X19 XXX 2XX | | X19 XXX 2XX |
| 2 | X18 XXX 4XX | | X18 XXX 4XX |
+-----------+--------------+--------------+-------------+
好的,我需要一些“动态”,因为将来表phone_categories 可以增长。
everyone i would like to perform a query on MySQL with dynamic rows.
Imagine this:
table phones_categories
+----+------------+
| id | name |
+----+------------+
| 1 | Home Phone |
| 2 | Cell Phone |
| 3 | Fax |
+----+------------+
table phones
+----+-----------+-------------------+--------------+
| id | entity_id | phone_category_id | phone_number |
+----+-----------+-------------------+--------------+
| 1 | 1 | 1 | X19 XXX 2XX |
| 2 | 1 | 3 | X19 XXX 2XX |
| 3 | 2 | 1 | X18 XXX 4XX |
| 4 | 2 | 3 | X18 XXX 4XX |
+----+-----------+-------------------+--------------+
i would like to have the following output:
+-----------+--------------+--------------+-------------+
| entity_id | Home Phone | Cell Phone | Fax |
+-----------+--------------+--------------+-------------+
| 1 | X19 XXX 2XX | | X19 XXX 2XX |
| 2 | X18 XXX 4XX | | X18 XXX 4XX |
+-----------+--------------+--------------+-------------+
Ok i need some "dynamic" becacuse on the future the table phone_categories can grow.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这称为“数据透视表”或“交叉表查询”。仅 MySQL 无法动态地完成此操作。您始终需要提前知道列名称,因此,如果您使用编程/脚本语言进行输出,则可以使用它通过
for
循环动态构建 SQL 语句。已经确定了类别。但查询将如下所示:
您尚未识别任何编程语言,因此这里有一些用于生成查询的伪代码:
This is called a "pivot table" or "crosstab query". MySQL alone cannot do this dynamically. You always need to know the column names ahead of time, so if you are using a programming/scripting language for your output you can use it to dynamically build up the SQL statement with a
for
loop after you've determined the categories.But the query will look like:
You haven't identified any programming language, so here's some pseudocode to generate the query: