我喜欢对关联选择使用自我解释的名称,有时甚至必须避免重复,所以我经常使用 AS 关键字。但这给我的左连接带来了一些麻烦。
这有效:
$sql = "SELECT *,
projects.id as projects_id
FROM projects";
$sql .= " LEFT JOIN".
" (SELECT
projectfiles.id as projectfiles_id,
projectfiles.fileID as projectfiles_fileID,
projectfiles.projectID as projectfiles_projectID
FROM projectfiles
) AS projectfiles".
" ON projects.id = projectfiles_projectID";
但是,现在我最终得到了来自 的无用数据projects
,因为它还获取了我不需要的字段userID
和。name
它也拿起了 id 两次。
所以我尝试将其更改为;
$sql = "SELECT
projects.id as projects_id
FROM projects";
随着上线成为
" ON projects_id = projectfiles_projectID";
但这给出了错误Unknown column projects_id
所以我尝试了
" ON projects.projects_id = projectfiles_projectID";
但仍然是同样的错误
然后我开始试验,并尝试(作为测试)
$sql = "SELECT id,name,userID FROM projects";
$sql .= " LEFT JOIN".
" (SELECT
projectfiles.id as projectfiles_id,
projectfiles.fileID as projectfiles_fileID,
projectfiles.projectID as projectfiles_projectID
FROM projectfiles
) AS projectfiles".
" ON projects.id = projectfiles_projectID";
令我惊讶的是, LEFT JOIN 似乎根本没有收到任何东西。
代码:
$sql = "SELECT id,name,userID FROM projects";
$sql .= " LEFT JOIN".
" (SELECT
projectfiles.id as projectfiles_id,
projectfiles.fileID as projectfiles_fileID,
projectfiles.projectID as projectfiles_projectID
FROM projectfiles
) AS projectfiles".
" ON projects.id = projectfiles_projectID";
$res = mysql_query($sql);
if(!$res) die(mysql_error());
if(mysql_num_rows($res) > 0)
{
$rownum = 0;
while($row = mysql_fetch_assoc($res))
{
print_r($row);
echo "<br/><br/>";
$rownum++;
}
}
输出:
这很奇怪,因为该projectID只有一行,projects
但有3行projectfiles
......我做错了什么?