1

我有一个“个人资料”表

  1. 用户身份
  2. 钥匙
  3. 核心价值

显然,当用户登录时,userid 可以有很多行,我将 userdata 存储在 session_var 中,查询使用 3 个表:

  1. 用户
  2. 简介
  3. 打开ID

我有这个,

$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如何处理重复键?

4

2 回答 2

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

或者您将 agroup by与您希望将数据分组的列一起使用。

最后,如果您想将多行数据返回到单个字段(但它们不同),您可以使用 mysqlgroup_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)

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

于 2012-08-22T09:24:27.800 回答
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”。

于 2012-08-22T09:50:17.417 回答