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

一个针对“bouncing”表的MySQL查询选择

  •  0
  • Vuk  · 技术社区  · 15 年前

    所以,为了简单起见,我有一个包含两个字段的主表-第一个是属性,第二个是属性值。如果第二个字段设置为引用另一个表中的值,则在括号中表示。

    例子:

                     MASTER_TABLE:
    Attr_ID |  Attr_Val
    --------+-----------
       1    | 23(table1)   --> 23rd value from `table1`
       2    | ...
       1    | 42           --> the number 42
       1    | 72(table2)   --> 72nd value from `table2`
       3    | ...
       1    | txt          --> string "txt"
       2    | ...
       4    | ...
    
    
                     TABLE 1:
     Val_Id |  Value
    --------+-----------
       1    | some_content
       2    | ...
       .    | ...
       .    | ...
       .    | ...
      23    | some_content
       .    | ...
    
    

    是否可以执行 单个查询 在SQL中(不分析应用程序内部的结果并重新查询数据库),它将通过主表和给定的 <attr_id> 仅获取引用其他表的属性( e、 g.23(表1),72(表2)。。。 ),然后从括号中解析表名( e、 g.表1、表2。。。 )并执行查询以获取( 23号,72号。。。 )价值( e、 g.一些内容 )从引用的表中?

    我做了一些事情,它解析表名的Attr\u Val,但是我不知道如何将它分配给一个字符串,然后用这个字符串进行查询。

    PREPARE pstmt FROM 
        "SELECT * FROM information_schema.tables 
         WHERE TABLESCHEMA = '<my_db_name>' AND TABLE_NAME=?"; 
    
     SET @str_tablename = 
       (SELECT table.tablename FROM
           (SELECT @string:=(SELECT <string_column> FROM <table> WHERE ID=<attr_id>) as String,
                @loc1:=length(@string)-locate("(", reverse(@string))+2 AS from,
                @loc2:=length(@string)-locate(")", reverse(@string))+1-@loc1 AS to,
                substr(@string,@loc1, @loc2) AS tablename
           ) table
       );  <--this returns 1 rows which is OK
    
    EXECUTE pstmt USING @str_tablename; <--this then returns 0 rows
    

    有什么想法吗?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Daniel Rhoden    15 年前

    我喜欢这种方法的纯洁性,如果成功的话。但我认为你在制造一个维修炸弹。有了这样的疗法,谁还需要生病?

    从来没有人说过一个网站“天哪,他们的数据肯定是纯的!”他们对正在进行的数据处理表示赞赏。我不建议你在这件事上手忙脚乱。我保证你的竞争对手不是。