【问题标题】:Combining mysql statements from different table depending on the column value根据列值组合来自不同表的mysql语句
【发布时间】:2015-07-13 00:59:56
【问题描述】:

我需要有关如何最好地处理这种情况的帮助。

我有 3 张桌子,比如 A、B、C。

表 A 有一列 categoryID,其中 G(好)或 B(坏)。

  • 如果A中的categoryID是G,则该行的信息在表B中。
  • 如果categoryID为B,则该行的信息在C中。

例如,如果我在表 A 中有 2 条记录。

对于第一条记录,categoryID 是 G。我需要从表 B 中获取第一条记录的数据。

对于第二条记录,categoryID 是 B,我需要从表 C 中获取第二条记录的数据。

我正在使用 MySQL 程序。我尝试过用例,但似乎不起作用。

我想在一个程序中实现这一点。表 B 和 C 具有表 A 中的外键引用列。

【问题讨论】:

  • 贴出你的程序。

标签: mysql database stored-procedures case


【解决方案1】:

一种方法是两个left joins。您的问题对列名的真正含义有点模糊,但方法是这样的:

select a.*, coalesce(b.col1, c.col1) as col1, coalesce(b.col2, c.col2) as col2
from a left join
     b
     on a.categoryId = 'G' and a.bid = b.bid left join
     c
     on a.categoryid = 'B' and a.cid = c.cid;

【讨论】:

    猜你喜欢
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 2013-12-16
    • 2022-11-15
    相关资源
    最近更新 更多