sql将resultset连接成一行

时间:2012-08-22 09:22:21

标签: php sql join

我有一个带

的“个人资料”表
  1. 用户ID
  2. key_value
  3. 显然,userid可以有很多行 当用户登录时,我将userdata存储在session_var中 该查询使用3个表:

    1. 用户
    2. 简档
    3. 的OpenID
    4. 我有这个,

      $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";
      

      但它返回多行,其中包含重复数据,具体取决于“profiles”表中的行数

      这不是我想要的。如果可能的话,我需要一行中的所有数据

      什么是最有效的解决方案?我还需要它存储在php数组中。 php如何处理重复键?

2 个答案:

答案 0 :(得分: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()函数查看多个列或您手动输入的值,就像我一样,并返回一个很棒的标识符来发现您丢失的字段。它将从左到右评估空值。

答案 1 :(得分: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";

配置文件列的输出类似于:“key1 = value1& key2 = value2”。