MySQL mysql从其他表中选择id和name并加入查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13652876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mysql select id and name from other table and join query
提问by user1829014
i have 2 table named projects and tasks
我有 2 个名为项目和任务的表
in projects table i have:
在项目表中,我有:
id name
---------
1 some
in tasks table i have:
在任务表中我有:
id name project_id
----------------------
1 some 1
Now,how can i select * from task table and get the 'name' from projects table by 'project_id' in table tasks?
现在,如何从任务表中选择 * 并通过表任务中的“project_id”从项目表中获取“名称”?
thanks
谢谢
回答by Denys Séguret
select task.id, task.name, proj.id, proj.name
from tasks task left join projects proj on proj.id=task.project_id;
Using left joinensures you get something even if there is no record in the projects table. If you want to ensure coherency, you may do
即使项目表中没有记录,使用左连接也能确保你得到一些东西。如果你想确保一致性,你可以这样做
select task.id, task.name, proj.id, proj.name
from tasks task, projects proj
where proj.id=task.project_id;
回答by Melanie
SELECT t.*, p.[name] FROM tasks t
INNER JOIN projects p
ON t.project_id = p.[id]
WHERE t.project_id = ____
You fill in _with the project_id you want
你用你想要的project_id填写_