0

我有下表命名attributes

| identifier | attribute | value      |
|------------|-----------|------------|
| 23         | myKey     | myValue    |
| 24         | hisKey    | hisValue   |
| 25         | herKey    | herValue   |
| 23         | otherKey  | otherValue |

我想进行 SQL 选择查询,它选择上述行,按它们的标识符对它们进行分组,并使用attribute作为键和value作为键的值。

这意味着看起来像上面的表应该变成以下 PHP 数组:

Array
(
    [0] => Array
        (
            [identifier] => 23
            [myKey] => myValue
            [otherKey] => otherValue
        )

    [1] => Array
        (
            [identifier] => 24
            [hisKey] => hisValue
        )

    [2] => Array
        (
            [identifier] => 25
            [herKey] => herValue
        )

)

我尝试了以下 SQL 查询:

SELECT attributes.value as atttributes.attribute FROM attributes GROUP BY identifier

这将给出以下错误:

未捕获的异常“PDOException”,带有消息“SQLSTATE [42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“.attribute FROM attributes GROUP BY identifier”附近使用正确的语法

有谁知道这样做的方法?

4

2 回答 2

1

您的错误来自拼写错误。不要在别名中指定表。

SELECT attributes.value as atttributes.attribute FROM attributes GROUP BY identifier

这是更正:

SELECT attributes.value as attribute FROM attributes GROUP BY identifier

然而,它不会得到你想要的。MySQL 将始终返回每行中具有相同列数的结果。

您需要使用循环在代码中实现这一点。使用 ORDER BY 代替 GROUP BY,并且每当标识符更改时,启动另一个数组。

于 2012-07-12T18:06:48.423 回答
1

答案是您不能以合理的方式使用 SQL 执行此操作。

于 2012-07-12T18:20:33.597 回答