'on子句'中的未知列(LEFT JOIN)

时间:2014-07-11 02:09:13

标签: mysql sql

我有一个包含表PagesUsers,主键PageIdUserId的数据库。

Pages包含引用UserId_ModifiedBy的外键字段UserId_CreatedByUsers

我正在尝试创建一个将从页面返回字段的查询,以及Users中有关UserId_ModififedByUserId_CreatedBy引用的用户的字段。

这就是我一直努力做的事情:

        $query =   "SELECT 
                        Pages.PageId, 
                        Pages.PageUniqueId,
                        Pages.Slug, 
                        Pages.Name,
                        Pages.Description, 
                        Pages.Keywords,
                        Pages.Layout, 
                        Pages.CustomStylesheet,
                        Pages.PageTypeId, 
                        Pages.CreatedDate,
                        Pages.ModifiedDate,

                        Users_Modified.UserUniqueId AS Modified_User_UserUniqueId,
                        Users_Modified.FName AS Modified_User_FName,
                        Users_Modified.LName AS Modified_User_LName,

                        Users_Created.UserUniqueId AS Created_User_UserUniqueId,
                        Users_Created.FName AS Created_User_FName,
                        Users_Created.LName AS Created_User_LName

                    FROM Pages
                        LEFT JOIN Users AS Users_Modified ON (Users.UserId = Pages.UserId_ModifiedBy)
                        LEFT JOIN Users AS Users_Created ON (Users.UserId = Pages.UserId_CreatedBy)";

预期行将返回:

[
  PageID: ...,
  PageUniqueId: ...,
  Slug: ...,
  Name: ...,
  ..
  ..
  Modified_User_UserUniqueId: ...,
  Modified_User_FName: ...,
  Modified_User_LName: ...,
  Created_User_UserUniqueId: ...,
  Created_User_FName: ...,
  Created_User_LName: ...
]
唉,我得到了SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Users.UserId' in 'on clause'UserIdUsers中的有效列,我尝试过使用和不使用别名等等。但我似乎无法让它工作,所以我必须遗漏一些东西。

2 个答案:

答案 0 :(得分:5)

您需要使用on子句中的别名:

    FROM Pages LEFT JOIN 
         Users AS Users_Modified
         ON Users_Modified.UserId = Pages.UserId_ModifiedBy LEFT JOIN
         Users AS Users_Created
         ON Users_Created.UserId = Pages.UserId_CreatedBy

答案 1 :(得分:0)

在我的情况下,该错误是由于FROM关键字中的外观位置引起的:

FROM TableA ta,TableB tb左联接TableC tc ON tc.login = ta.login

在更改工作台位置的同时无效,有效

FROM表B tb,表A ta 左连接TableC tc ON tc.login = ta.login