在SQL查询具有别名时获取列值

时间:2013-09-21 11:47:40

标签: php mysql pdo alias

我有一个在其中包含别名的SQL查询。问题是,当我尝试获取列的值时,它不会显示正确的值:

$sql = "SELECT p.ID, p.ProfileID, p.ModuleID, p.View, p.Add, p.Edit, p.Delete, m.Name, m.ID FROM permission AS p, module AS m WHERE p.ModuleID = m.ID ORDER BY p.ProfileID ASC, m.Name ASC";

    $result = array();
    $i = 0;
    foreach ($this->dbconnect->query($sql) as $row)
    {
        $result[$i] = array(
        'ID' => $row['p.ID'],
        'ProfileID' => $row['p.ProfileID'],
        'ModuleID' => $row['p.ModuleID'],
        'View' => $row['p.View'],
        'Add' => $row['p.Add'],
        'Edit' => $row['p.Edit'],
        'Delete' => $row['p.Delete']);

        $i += 1;
    }

在数据库中,运行时显示没有值,实际上是10。

如果我将上述代码更改为以下代码:

$sql = "SELECT p.ID, p.ProfileID, p.ModuleID, p.View, p.Add, p.Edit, p.Delete, m.Name, m.ID FROM permission AS p, module AS m WHERE p.ModuleID = m.ID ORDER BY p.ProfileID ASC, m.Name ASC";

    $result = array();
    $i = 0;
    foreach ($this->dbconnect->query($sql) as $row)
    {
        $result[$i] = array(
        'ID' => $row['ID'],
        'ProfileID' => $row['ProfileID'],
        'ModuleID' => $row['ModuleID'],
        'View' => $row['View'],
        'Add' => $row['Add'],
        'Edit' => $row['Edit'],
        'Delete' => $row['Delete']);

        $i += 1;
    }

奇迹般地,正在运行会显示m.ID而不是p.ID的值。奇怪为什么第一个例子是不正确的。我在这里错过了什么吗?

2 个答案:

答案 0 :(得分:2)

你应该这样......

SELECT p.ID as p_ID, ...

'ID' => $row['p_ID'],

答案 1 :(得分:0)

在SELECT中为每列使用别名:

$sql = "SELECT p.ID AS permission_id, p.ProfileID, p.ModuleID, p.View, p.Add, p.Edit, p.Delete, m.Name, m.ID AS module_id FROM permission AS p, module AS m WHERE p.ModuleID = m.ID ORDER BY p.ProfileID ASC, m.Name ASC";

然后:

foreach(...)
{
    $result[$i] = array(
    'Perm_ID' => $row['permission_id'],
    'Module_ID' => $row['module_id'],
    ...
}