我从mysql select dynamic row values as column names, another column as value找到了我的问题的答案。这是SQL:
SELECT CONCAT(
'SELECT dm_generics.dm_id', GROUP_CONCAT(CONCAT('
, t_', REPLACE(field_name, '', ''), '.field_value
AS ', REPLACE(field_name, '', ''), ''
) SEPARATOR ''),
' FROM dm_generics ', GROUP_CONCAT(CONCAT('
LEFT JOIN dm_generics AS t_', REPLACE(field_name, '', ''), '
ON dm_generics.dm_id = t_', REPLACE(field_name, '', ''), '.dm_id
AND t_', REPLACE(field_name, '', ''), '.field_name = ', QUOTE(field_name)
) SEPARATOR ''),
' GROUP BY dm_generics.dm_id'
) INTO @qry FROM (SELECT DISTINCT field_name FROM dm_generics) t;
PREPARE stmt FROM @qry;
EXECUTE stmt;
但是,我很困惑如何在PDO中执行该查询。
我曾试图使用这样的东西:
$stmt = $dbh->prepare($sql);
if($stmt->execute())
{
$object = $stmt->fetchAll(PDO::FETCH_OBJ);
return $object;
}
我没有使用PDO :: prepare,而是尝试使用PDO查询
$stmt = $dbh->query($sql);
但是,我有一个空数组或null。我猜这个查询有些“错误”,也许是因为里面有一个MySQL变量?
以下是答案http://sqlfiddle.com/#!2/6e689/1
提供的小提琴那么,您能否告诉我问题是什么以及如何使其发挥作用?
更新
作为Your Common Sense建议,现在我可以使这些查询起作用。这是代码:
$sql = "SELECT CONCAT(
'SELECT dm_generics.dm_id', GROUP_CONCAT(CONCAT('
, t_', REPLACE(field_name, '', ''), '.field_value
AS ', REPLACE(field_name, '', ''), ''
) SEPARATOR ''),
' FROM dm_generics ', GROUP_CONCAT(CONCAT('
LEFT JOIN dm_generics AS t_', REPLACE(field_name, '', ''), '
ON dm_generics.dm_id = t_', REPLACE(field_name, '', ''), '.dm_id
AND t_', REPLACE(field_name, '', ''), '.field_name = ', QUOTE(field_name)
) SEPARATOR ''),
' GROUP BY dm_generics.dm_id'
) INTO @qry FROM (SELECT DISTINCT field_name FROM dm_generics) t;";
$sql2 = "PREPARE stmt FROM @qry;";
$sql3 = "EXECUTE stmt;";
$stmt = $dbh->prepare($sql);
$stmt2 = $dbh->prepare($sql2);
$stmt3 = $dbh->prepare($sql3);
if($stmt->execute() && $stmt2->execute() && $stmt3->execute())
{
return $stmt3->fetchAll(PDO::FETCH_OBJ);
}