我有一个带有的"配置文件"表
- userid
- 钥匙
- 关键字值
显然,userid可以有很多行当用户登录时,我将用户数据存储在session_var中查询使用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如何处理重复的密钥?
您可能想要类似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()
函数查看多个列或像我一样手动输入的值,并返回一个很好的标识符来查找丢失的字段。它将从左到右计算空值。
您可以使用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";
配置文件列的输出类似于:"key1=value1&key2=value2"。