mysql从其他表中选择ID和名称并加入查询 [英] mysql select id and name from other table and join query

查看:102
本文介绍了mysql从其他表中选择ID和名称并加入查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个表分别命名为项目和任务

i have 2 table named projects and tasks

在项目表中,我有:

id   name
---------
1    some

在任务表中,我有:

id   name   project_id
----------------------
1    some        1

现在,我该如何从任务表中选择*并在表任务中通过"project_id"从项目表中获得名称"?

Now,how can i select * from task table and get the 'name' from projects table by 'project_id' in table tasks?

谢谢

推荐答案

select task.id, task.name, proj.id, proj.name
from tasks task left join projects proj on proj.id=task.project_id; 

使用左联接可以确保即使在这里您也能得到一些东西在项目表中没有记录.如果要确保连贯性,可以这样做

Using left join ensures 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; 

这篇关于mysql从其他表中选择ID和名称并加入查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆