D
D
Darth Vader2020-06-25 17:20:23
MySQL
Darth Vader, 2020-06-25 17:20:23

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'

To test the search where the search is not working try this
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'

Watch online here https://paiza.io/projects/l0kYgCromPmHD_gGjf5PrQ?l...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2020-06-25
@blackdarthvader

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

Or if without selection, then
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

M
Melkij, 2020-06-25
@melkij

On one field from the table it is simpler a subquery.

select 
  (select deal_id from table_1 where item_id = 9041) as deal_id_1
  (select deal_id from table_2 where item_id = 9041) as deal_id_2
  (select deal_id from table_3 where item_id = 9041) as deal_id_3

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question