2011-09-23 58 views
0

每個人我都想用動態行對MySQL進行查詢。mysql動態行

想象一下:

表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

爲什麼貶我的問題? – workdreamer

回答

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` 
+0

Ruby on Rails:S – workdreamer

+0

謝謝你的幫助! – workdreamer