我在4张桌子,1张主桌子和3张小桌子上工作。主表称为“文档”,它是来自其他3个小表的引用和ID,它们是:重要性,自然,access_level。
e.g.
(Table1) document
document_id | title | file_name | importance_id | nature_id | access_level_id
-----------------------------------------------------------------------------
1 | Food | food.docx | 1 | 1 | 1
(Table2) importance
importance_id | name
--------------------
1 | High
(Table3) nature
nature_id | name
----------------
1 | General
(Table4) nature
access_level_id | name
----------------------
1 | Public
我想要做的是显示所有文档(使用SELECT),并将其ID替换为相应的名称..像这样:
document_id | title | file_name | importance | nature | access_level
-----------------------------------------------------------------------------
1 | Food | food.docx | High | General | Public
我尝试使用此查询,但效果不佳:
SELECT `document_id`, `title`, `file_name`, `date_of_archiving`, `duration_of_life`, importance.name as importance, nature.name as nature, access_level.name as access_level
FROM document, importance, nature, access_level
WHERE importance.importance_id = document.document_id
AND nature.nature_id = document.nature_id
AND access_level.access_level_id = document.access_level_id;
那我怎么能做到这一点?
提前致谢:)
答案 0 :(得分:0)
使用JOINS而不是您正在使用的过时语法。调试更清晰,更容易。并保存键入使用表别名。如下:
SELECT
document_id,
title,
file_name,
date_of_archiving,
duration_of_life,
i.NAME AS [importance],
n.name as [nature],
al.name as [access_level]
FROM
DOCUMENT D
JOIN importance i ON i.Importance_id = D.importance_id
JOIN nature n ON n.nature_id = D.nature_id
JOIN access_level al on al.access_level_id = D.access_level_id
答案 1 :(得分:0)
如果希望行不返回空值
,请使用内部联接SELECT
document_id,
title,
file_name,
date_of_archiving,
duration_of_life,
i.NAME AS [importance],
n.name as [nature],
al.name as [access_level]
FROM
DOCUMENT D
INNER JOIN importance i ON i.Importance_id = D.importance_id
INNER JOIN nature n ON n.nature_id = D.nature_id
INNER JOIN access_level al on al.access_level_id = D.access_level_id
答案 2 :(得分:0)
使用此代码:
SELECT
Document_id,
Title,
File_name,
i.name AS Importance,
n.name AS Nature,
s.name AS Access_level
FROM Document d
INNER JOIN importance i ON i.importance_id = d.importance_id
INNER JOIN nature n ON n.nature_id = d.nature_id
INNER JOIN nature s ON s.access_level_id = d.access_level_id