5

我喜欢对关联选择使用自我解释的名称,有时甚至必须避免重复,所以我经常使用 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......我做错了什么?

4

5 回答 5

1

使用查询的简短形式:

$sql = "SELECT projects.id,projects.name,projects.userID FROM projects LEFT JOIN
       projectfiles ON projects.id = projectfiles.projectID";
于 2012-06-08T09:02:29.707 回答
1
SELECT p.*, pf.id, pf.fileId
FROM projects p LEFT JOIN projectfiles pf 
on p.id = pf.projectID

你可以使用“as”来做你想做的事。不需要子选择。

于 2012-06-08T09:03:14.100 回答
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
于 2012-06-08T09:16:07.597 回答
0
$sql = "SELECT p.id,p.name,p.userID FROM projects p";

$sql .= " LEFT JOIN".
    " projectfiles pf ".
    " ON p.id = p.projectID";
于 2012-06-08T09:05:23.777 回答
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";
于 2012-06-08T09:30:09.927 回答