我喜欢将自解释名称用于关联选择,有时甚至必须避免重复,因此我使用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线成为
" 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++;
}
}
输出:
这很奇怪,因为projects
中只有一行,projectfiles
中只有一行有该项目ID ...我做错了什么?
答案 0 :(得分:1)
使用简短形式的查询:
$sql = "SELECT projects.id,projects.name,projects.userID FROM projects LEFT JOIN
projectfiles ON projects.id = projectfiles.projectID";
答案 1 :(得分:1)
SELECT p.*, pf.id, pf.fileId
FROM projects p LEFT JOIN projectfiles pf
on p.id = pf.projectID
您可以使用“as”来执行操作。不需要子选择。
答案 2 :(得分:1)
仅从projectfiles
表中选择:
$sql = "SELECT projectfiles.*,
projects.id as projects_id
FROM projects";
// rest of the code is the same
<强>更新强>
$sql = "SELECT projectfiles.* FROM projects";
// rest of the code is the same
答案 3 :(得分:0)
$sql = "SELECT p.id,p.name,p.userID FROM projects p";
$sql .= " LEFT JOIN".
" projectfiles pf ".
" ON p.id = p.projectID";
答案 4 :(得分:0)
$sql = "SELECT prj.id as prjId,
prj.name as prjName,
prj.userID as prjUid,
pf.id as pfId,
pf.fileID as pfFileId,
pf.projectID as pfProjecId
FROM projects as prj
LEFT JOIN projectfiles AS pf
ON prj.id = pf.projectID";