【问题标题】:Mysql query to search same column in different tablesMysql查询在不同表中搜索同一列
【发布时间】:2015-08-30 13:48:53
【问题描述】:

我有三张桌子

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 ║
 ╚════╩══════════════╩══════╝

我只能使用普通的 Mysql 查询。 我需要加入 table_atable_b 以找到 community 并且如果没有对应于 communitycommunity tablea 中的strong>MID 我需要加入table_c 才能获得community。如何实现? 请帮助我。谢谢!

【问题讨论】:

  • 为什么会有两张相似的表?所以你的数据库中有冗余
  • 表b和表c的数据在结构上有什么区别?如果该数据在结构上没有区别,而只是在 meaning 上——那么您可能更应该使用 one 表,并附加一列可用于区分“类型”b 或 c 的数据。
  • 两张表完全一样,但来自不同的学校..我不能改变结构。

标签: mysql


【解决方案1】:

您可以将LEFT JOIN 与两个表一起使用,然后使用COALESCE 选择第一个现有项目:

SELECT a.Id, a.MID, COALESCE(b.Community, c.Community, '') as Community
FROM table_a a 
    LEFT JOIN table_b b ON a.MID = b.MID
    LEFT JOIN table_c c ON a.MID = c.MID

此时如果table_b中有匹配数据,则使用b.Community,否则如果table_c中有匹配数据,则使用c.Community。如果任何一个表中都不匹配,则使用空白空间。

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 2013-08-27
    相关资源
    最近更新 更多