Answer the question
In order to leave comments, you need to log in
How to query 3 tables with where condition?
Hello, there are three tables table_1, table_2, table_3
I need 1 query to take data from three tables at once, but with the data search condition on the item_id column, which is present in 3 tables at once. I managed to display the data, but I ran into a problem, if there is no item_id in one of the tables, then the search does not work, I do not know the MYSQL syntax and operators very well, so this is a huge problem for me.
That is, I need to search by item_id (item_id is always known to me) in three tables table_1, table_2, table_3 and display the values of these columns deal_id, track_id, waybill_id, if they exist.
Please help me make the right request. For example, if there is no data in any of the tables, then write null in these columns when outputting.
I wrote this request, it works
select t1.item_id, t1.deal_id, t2.track_id, t3.waybill_id
from table_1 as t1
join table_2 as t2 on t2.item_id = t1.item_id
join table_3 as t3 on t3.item_id = t1.item_id
where t1.item_id = '9026'
select t1.item_id, t1.deal_id, t2.track_id, t3.waybill_id
from table_1 as t1
join table_2 as t2 on t2.item_id = t1.item_id
join table_3 as t3 on t3.item_id = t1.item_id
where t1.item_id = '9041'
Answer the question
In order to leave comments, you need to log in
select ids.id, t1.deal_id, t2.track_id, t3.waybill_id from
(select '9014' as id) as ids
left join table_1 as t1 on ids.id = t1.item_id
left join table_2 as t2 on ids.id = t2.item_id
left join table_3 as t3 on ids.id = t3.item_id
select ids.id, t1.deal_id, t2.track_id, t3.waybill_id from
(select t1.item_id as id from table_1 union t2.item_id from table_2 union t3.item_id from table_3) as ids
left join table_1 as t1 on ids.id = t1.item_id
left join table_2 as t2 on ids.id = t2.item_id
left join table_3 as t3 on ids.id = t3.item_id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question