Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...