2012-07-12 89 views
0

我有以下表命名attributes其他列选择列

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

我想打它选择上述行SQL SELECT查询,通过他们的识别符组他们,并使用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

这将给出以下错误:

Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.attribute FROM attributes GROUP BY identifier' at line 1'

D任何人都知道如何做到这一点?

+2

为什么你不能循环访问记录并使用PHP构建该数组? – 2012-07-12 17:58:47

+0

我不知道你在找什么SQL输出。请举一个例子。 – RedFilter 2012-07-12 18:02:54

+0

我可以。那没问题。我只是认为用SQL查询来做它会更好,甚至可以提供更好的性能。 – simonbs 2012-07-12 18:03:34

回答

1

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

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

这里的修正:

SELECT attributes.value as attribute FROM attributes GROUP BY identifier 

但是,它不会得到你想要的,你想要的。 MySQL将总是返回每行中具有相同列数的结果。

你需要在循环代码中实现它。而不是GROUP BY,使用ORDER BY,并且每当标识符更改时,启动另一个数组。

+0

我确实有一个错字。但是,当错字纠正后,我会得到同样的错误。似乎我需要在代码中执行此操作:-) – simonbs 2012-07-12 18:09:14

+0

@SimonBS,Oops,另外,不要在别名中指定表名。 :) – 2012-07-12 18:13:52

1

答案是你不能用合理的方式用SQL来做到这一点。