Mysql query to search same column in different tables -
i have 3 tables
table_a
╔════╦══════╗ ║ id ║ mid ║ ╠════╬══════╣ ║ 1 ║ 5996 ║ ║ 2 ║ 148 ║ ║ 3 ║ 101 ║ ║ 4 ║ 5636 ║ ║ 5 ║ 143 ║ ║ 6 ║ 101 ║ ║ 7 ║ 959 ║ ║ 8 ║ 148 ║ ╚════╩══════╝
table_b
╔════╦══════════════╦══════╗ ║ id ║ community ║ mid ║ ╠════╬══════════════╬══════╣ ║ 1 ║ jeff atwood ║ 5636 ║ ║ 2 ║ geoff dalgas ║ 148 ║ ║ 3 ║ neal marley ║ 101 ║ ║ 4 ║ joel spolsky ║ 959 ║ ╚════╩══════════════╩══════╝
table_c
╔════╦══════════════╦══════╗ ║ id ║ community ║ mid ║ ╠════╬══════════════╬══════╣ ║ 1 ║ jim atwood ║ 3212 ║ ║ 2 ║ rim dalgas ║ 428 ║ ║ 3 ║ jarrod dixon ║ 388 ║ ║ 4 ║ noel spolsky ║ 339 ║ ╚════╩══════════════╩══════╝
i can use plain mysql query. need join table_a table_b find community , in case there no community corresponding mid in tablea need join table_c community.how accomplish that? please me.thank you!
you can use left join
both tables , select first existing item using coalesce
:
select a.id, a.mid, coalesce(b.community, c.community, '') community table_a left join table_b b on a.mid = b.mid left join table_c c on a.mid = c.mid
in case if have matching data in table_b
, b.community
used, otherwise if there matching data in table_c
, c.community
used. if there no match in either of tables, empty space used.
Comments
Post a Comment