mysql dynamic rows
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:
+-----------+--------------+--------------+--------开发者_StackOverflow中文版-----+
| 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.
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:
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
You haven't identified any programming language, so here's some pseudocode to generate the query:
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`
精彩评论