代码之家  ›  专栏  ›  技术社区  ›  anon

使用列作为concat的表连接

  •  0
  • anon  · 技术社区  · 6 年前

    我一直在尝试联接另一个表,该表的名称与另一个表的列中的值匹配。

    如果我将表名硬编码为匹配的表 __gun 它工作得很好,但我不能得到col值要使用+concat下划线开始。

    问题在于 left join

    left join CONCAT('__', b.related_table) c on b.related_id = c.id

    我需要在联接中使用相关的表列。在它前面加上。

    尝试:

            SELECT a.*, c.*, b.equipable, b.related_table FROM inventory a
            inner join items b on a.item_id = b.id
            left join CONCAT('__', b.related_table) c on b.related_id = c.id
            WHERE 1=1
            and a.id = :inventory_id
            and a.user_id = :user_id
    

    enter image description here


            SELECT a.*, c.*, b.equipable, b.related_table FROM inventory a
            inner join items b on a.item_id = b.id
            left join '__'+b.related_table c on b.related_id = c.id
            WHERE 1=1
            and a.id = :inventory_id
            and a.user_id = :user_id
    

    enter image description here


            SELECT a.*, c.*, b.equipable, b.related_table FROM inventory a
            inner join items b on a.item_id = b.id
            left join "__"+Cast(b.related_table as nvarchar(4000)) c on b.related_id = c.id
            WHERE 1=1
            and a.id = :inventory_id
            and a.user_id = :user_id
    

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  0
  •   Rick James diyism    6 年前

    不能构造表名。

    通常 有多个“相同”表的设计不好。

    计划B:编写一个使用 CONCAT , PREPARE EXECUTE ,和 DEALLOCATE_PREPARE 生成并运行查询。

        2
  •  0
  •   Muhammad Waheed Ray K.    6 年前

    你可以使用 Prepared Statements 或者你可以说动态SQL。遵循以下步骤:

    1. 使用 用于表名。
    2. 康卡特 获取所需的表名。
    3. 准备
    4. 执行 声明。
    5. 解除分配准备 发布事先准备好的声明。