2012-08-22 62 views
0

我有SQL JOIN結果集爲單列

  1. 用戶ID
  2. 鍵 「配置文件」 表
  3. key_value

明顯的用戶ID可以有很多行 當用戶登錄在我將userdata存儲在session_var中 查詢使用3個表格:

  1. 用戶
  2. 型材
  3. 的OpenID

我有這個,

$sql = "SELECT op.provider, g . * , gp . *, CONCAT(g.firstname, ' ', g.lastname) AS fullname 
    FROM openid AS op 
    INNER JOIN users AS g ON g.userid = op.userid 
    INNER JOIN profiles AS gp ON gp.userid = op.userid 
    WHERE op.openid =$openid"; 

但它返回與重複數據取決於有多少行是在 「配置文件」 表

多行

這不是我想要的。我需要一行中的所有數據(如果可能的話)

什麼是最有效的解決方案?我也需要它來存儲在一個php數組中。 PHP如何處理重複密鑰?

回答

1

你可能想要的東西就像一個distinct

$sql = "SELECT distinct op.provider, g . * , gp . *, CONCAT(g.firstname, ' ', g.lastname) AS fullname 
    FROM openid AS op 
    INNER JOIN users AS g ON g.userid = op.userid 
    INNER JOIN profiles AS gp ON gp.userid = op.userid 
    WHERE op.openid =$openid"; 

,否則,你使用你想擁有由分組數據的列group by

最後,如果你想多行數據返回到一個單一的領域(但它們是不同的),你可以使用MySQL group_concat()功能,可以這樣做:

mysql> select * from first; 
+------+-------+ 
| id | title | 
+------+-------+ 
| 1 | aaaa | 
| 2 | bbbb | 
| 3 | cccc | 
+------+-------+ 
3 rows in set (0.00 sec) 

mysql> select group_concat(id) as IDs, group_concat(title) as Titles from first; 
+-------+----------------+ 
| IDs | Titles   | 
+-------+----------------+ 
| 1,2,3 | aaaa,bbbb,cccc | 
+-------+----------------+ 
1 row in set (0.00 sec) 

好吧,我增加了一些額外的行我的示例表是這樣的:

mysql> select * from first; 
+------+-------+ 
| id | title | 
+------+-------+ 
| 1 | aaaa | 
| 2 | bbbb | 
| 3 | cccc | 
| 4 | NULL | 
| 5 | eeee | 
+------+-------+ 
5 rows in set (0.00 sec) 

,現在是group_concat返回此:

mysql> select group_concat(id) as IDs, group_concat(title) as Titles from first; 
+-----------+---------------------+ 
| IDs  | Titles    | 
+-----------+---------------------+ 
| 1,2,3,4,5 | aaaa,bbbb,cccc,eeee | 
+-----------+---------------------+ 
1 row in set (0.00 sec) 

但是你可以使用coalesce()功能很好地添加一個漂亮的佔位符,就像這樣:

mysql> select group_concat(id) as IDs, group_concat(coalesce(title,'NoValueSpecial')) as Titles from first; 
+-----------+------------------------------------+ 
| IDs  | Titles        | 
+-----------+------------------------------------+ 
| 1,2,3,4,5 | aaaa,bbbb,cccc,NoValueSpecial,eeee | 
+-----------+------------------------------------+ 
1 row in set (0.01 sec) 

coalesce()功能看無論是多列或手動輸入像我一樣的值,並返回一個偉大的標識符發現你失蹤領域。它將從零開始評估空值。

+0

它仍然返回兩行(因爲我在配置文件中有兩行) – Richard

+1

@Richard您可能想要使用我添加到答案中的'group_concat'函數將這些單獨的記錄組合到一行中。 – Fluffeh

+0

我不知道group by,但是group concat很有趣,如果我可以將它變成一個二維數組(userid將是相同的,但我需要組合鍵和相應的值),您是否有示例一羣由? – Richard

1

您可以使用GROUP CONCAT函數創建一個字符串,PHP可以使用parse_str解析算賬:

$sql = "SELECT distinct op.provider, g . * , GROUP_CONCAT(gp.`key` , '=' , gp.key_value SEPARATOR '&'), CONCAT(g.firstname, ' ', g.lastname) AS fullname 
    FROM openid AS op 
    INNER JOIN users AS g ON g.userid = op.userid 
    INNER JOIN profiles AS gp ON gp.userid = op.userid 
    WHERE op.openid =$openid"; 

的輸出配置文件列將是這樣的:「鍵1 =值&鍵2 =值」。

+0

謝謝,現在我有選擇 – Richard