Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join 2 tables SQL query

Tags:

sql

join

mysql

I'm trying to write a query for Select from 2 tables.

Tables are the following:

Table_1: 
id (int)
name (varchar)
status int (0,1)

Table_2: 
id (int)
table_1_id (int)
name (varchar)
time (datetime)

I need to select all the rows from Table_2 which are no older than 1 day and that are associated with table_1 with status 1. The way I do it now is using 2 queries and 2 foreach arrays, which is very inefficient. Could someone help me to write a query with join? Thank you for your time.

like image 818
John W Avatar asked Feb 01 '26 01:02

John W


1 Answers

No need of looping, you can do a JOIN between the tables like

select t2.*
from Table_2 t2 join Table_1 t1 on t2.table_1_id = t1.id
where t1.status = 1
and date(t2.`time`) = date(now() - interval 1 day);
like image 184
Rahul Avatar answered Feb 02 '26 17:02

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!