每个人我想用动态行执行MySQL查询。
想象一下:
table phones_categories
+----+------------+
| id | name |
+----+------------+
| 1 | Home Phone |
| 2 | Cell Phone |
| 3 | Fax |
+----+------------+
桌面电话
+----+-----------+-------------------+--------------+
| 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可以增长。
答案 0 :(得分:1)
这称为“数据透视表”或“交叉表查询”。仅MySQL不能动态地执行此操作。您总是需要提前知道列名,因此如果您使用编程/脚本语言输出,则可以在确定后使用它以for
循环动态构建SQL语句。类别。
但查询将如下所示:
SELECT
phones.entity_id,
CASE WHEN phones.phone_category_id = 1 THEN phones.phone_number ELSE NULL END AS `Home Phone`,
CASE WHEN phones.phone_category_id = 2 THEN phones.phone_number ELSE NULL END AS `Cell Phone`,
CASE WHEN phones.phone_category_id = 3 THEN phones.phone_number ELSE NULL END AS `Fax`
FROM phones
你还没有发现任何编程语言,所以这里有一些伪代码来生成查询:
categories = "SELECT id, name FROM phone_categories;"
foreach categories
sql_columns = sql_columns + " CASE WHEN phones.phone_category_id = " + categories.id + " THEN phones.phone_number ELSE NULL END AS `categories.name`