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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With