我正在尝试加入3张桌子。项目,状态,客户。查询的目标应该导致所有项目的当前状态为“已接收”。我也试图获取客户端名称以显示在结果表中。
这些表具有以下公共外键:client_ID,status_ID。
到目前为止,这是我的查询。我正在努力更好地了解联接。如果你可以提供关于我做错的评论以及非常适合的示例代码。
SELECT clients.clientName,
clients.Client_ID,
projects.Client_ID,
projects.projectNumber,
projects.projectName,
projects.expectedDate,
statuses.Status_ID,
statuses.status
FROM projects,
clients,
statuses
LEFT JOIN clients on projects.Client_ID = clients.Client_ID
LEFT JOIN statuses on projects.Status_ID = statuses.Status_ID
WHERE status = 'Received'
答案 0 :(得分:2)
尝试使用'JOIN'代替'LEFT JOIN'。还要删除from子句中的客户端和状态。我还会查询Status_ID而不是状态名称。
SELECT clients.clientName,
clients.Client_ID,
projects.Client_ID,
projects.projectNumber,
projects.projectName,
projects.expectedDate,
statuses.Status_ID,
statuses.status
FROM projects
JOIN clients on projects.Client_ID = clients.Client_ID
JOIN statuses on projects.Status_ID = statuses.Status_ID
WHERE statuses.status = 'Received'
答案 1 :(得分:0)
尝试下面的代码。
删除LEFT JOIN并使用WHERE条件和INNER JOIN ...
SELECT clients.clientName,
clients.Client_ID,
projects.Client_ID,
projects.projectNumber,
projects.projectName,
projects.expectedDate,
statuses.Status_ID,
statuses.status
FROM projects,
clients,
statuses
WHERE
clients on projects.Client_ID = clients.Client_ID AND
statuses on projects.Status_ID = statuses.Status_ID AND
status = 'Received'
这可能对您有所帮助,并提供您想要等待的记录。
答案 2 :(得分:0)
您应该只在FROM子句中有一个表名,否则您将多次连接表(ANSI语法)。另外,它有助于设置连接条件(我认为更容易阅读);并扩展表名(projects.status = ...)而不是(status = ...)。
另外,正如已经指出的那样,如果要返回'projects'行,“JOIN”而不是“LEFT JOIN”会强制存在相应的行。
SELECT clients.clientName, clients.Client_ID, projects.Client_ID,
projects.projectNumber,projects.projectName, projects.expectedDate,
statuses.Status_ID, statuses.status
FROM projects
LEFT JOIN clients ON clients.Client_ID = projects.Client_ID
LEFT JOIN statuses ON statuses.Status_ID = projects.Status_ID
WHERE statuses.status = 'Received'