简体   繁体   中英

mysql select id and name from other table and join query

i have 2 table named projects and tasks

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?

thanks

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; 
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM