Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql select id and name from other table and join query

Tags:

sql

mysql

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

like image 380
user1829014 Avatar asked Nov 30 '12 20:11

user1829014


People also ask

Which is faster select or join?

Which one will be faster probably depends on the size of tables - if TABLE1 has very few rows, then IN has a chance for being faster, while JOIN will likely be faster in all other cases. This is a peculiarity of MySQL's query optimizer.

What is dual table in MySQL?

MySQL allows DUAL to be specified as a table in queries that do not need data from any tables. In SQL Server DUAL table does not exist, but you could create one. The DUAL table was created by Charles Weiss of Oracle corporation to provide a table for joining in internal views.

Can we join same table in MySQL?

The self join is often used to query hierarchical data or to compare a row with other rows within the same table. To perform a self join, you must use table aliases to not repeat the same table name twice in a single query.


2 Answers

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; 
like image 79
Denys Séguret Avatar answered Sep 24 '22 14:09

Denys Séguret


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

like image 44
Melanie Avatar answered Sep 25 '22 14:09

Melanie