代码之家  ›  专栏  ›  技术社区  ›  Thiago Belem

MySQL动态连接

  •  1
  • Thiago Belem  · 技术社区  · 15 年前

    假设我的数据库中有这些表:

    items
    categories
    weapons
    shields
    swords
    

    我需要创建一个这样的连接:

    SELECT items.*, {swords}.*
    FROM items
    INNER JOIN categories
      ON categories.id = items.category_id # <-- here I know that the item is a sword
    INNER JOIN {swords}
      ON {swords}.item_id = item.id
    WHERE items.id = 12
    

    但是 {swords} 部分是动态的,因为我发现一个项目是一个 检查 categories.name 现场。

    如果 类别.名称 是“ “对此:

    SELECT items.*, shields.*
    FROM items
    INNER JOIN categories
      ON categories.id = items.category_id
    INNER JOIN shields
      ON shields.item_id = item.id
    WHERE items.id = 13
    

    我曾经 { } swords 把它当作变量来表示

    1 回复  |  直到 15 年前
        1
  •  1
  •   OMG Ponies    15 年前

    从技术上讲,您只能使用动态SQL来实现这一点,这意味着 MySQL's Prepared Statement syntax

    您可以使用左连接到各个表,但这意味着包括来自每个表(武器、盾牌、剑……)的许多列,如果类别不匹配,这些列将为空。试图从一个查询中提取数据是很可怕的。。。

    PS:为什么会有 SWORD 桌子?这不在保险单上吗 WEAPON