Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL how to join tables on two fields

Tags:

join

mysql

I have two tables with date and id fields. I want to join on both fields. I tried

JOIN t2 ON CONCAT(t1.id, t1.date)=CONCAT(t2.id, t2.date) 

that works, but it is very slow. is there a better way to do this?

like image 662
pedalpete Avatar asked Jan 31 '09 03:01

pedalpete


People also ask

How do I join two tables with two columns?

If you'd like to get data stored in tables joined by a compound key that's a primary key in one table and a foreign key in another table, simply use a join condition on multiple columns. In one joined table (in our example, enrollment ), we have a primary key built from two columns ( student_id and course_code ).

Can you join on 2 columns in SQL?

Yes: You can use Inner Join to join on multiple columns.


2 Answers

JOIN t2 ON t1.id=t2.id AND t1.date=t2.date 
like image 134
womble Avatar answered Sep 22 '22 17:09

womble


JOIN t2 ON (t2.id = t1.id AND t2.date = t1.date) 
like image 35
Chad Birch Avatar answered Sep 25 '22 17:09

Chad Birch