如何在sql中编写子查询来映射字典值

时间:2013-10-21 23:50:04

标签: mysql sql oracle postgresql

我有一个字典,它将整数映射到字符串,另一个表存储整数之间的关系:

    Dictionary (id, stringvalue)
    1      Where
    2      are you
    3      going
    4      This 
    5      is
    6      stackoverflow

   Table(col1, col2, col3)
   Col1    col2     col3
   1       2        3
   4       5        6

查询这两个表的步骤如下:

1. Given string map them to ids using dictionary
2. Given strings map them to corresponding column using Table, which gives an integer
3. Given ids which we got from step1 map them again to string and present the result to the user?

现在为了找出“Where are”之后的下一列值,我可以用以下形式查询:

   select d3.stringvalue from dictionary d1, dictionary d2, dictionary d3, Table t1 where
   d1.stringvalue='Where' and d1.id=Table.Col1 and d2.stringvalue='are' and d2.id=Table.Col2 and d3.id=Table.Col3;

我对上述查询的期望输出是:

      you

鉴于col1 = 1('Where'),Col2 = 2('Are')我想找出Col3的字符串值('你')?

然而,事实证明,对于更复杂的查询,这种从id到string的映射变得很麻烦。是否有某种方法可以将相同的查询转换为sql

中的简洁可读和简短查询

1 个答案:

答案 0 :(得分:1)

 select SUBSTRING(d2.stringvalue,5,7) AS "YOU" 
   from dictionary d1, dictionary d2, dictionary d3, Table t1
  where d1.stringvalue='Where' and
        d1.id=Table.Col1 and 
        SUBSTRING(d2.stringvalue,,3) ='are' and
        SUBSTRING(d2.stringvalue,5,7) ='you' and
        d2.id=Table.Col2 and 
        d3.id=Table.Col3;

如果您只需要“您”作为输出,则上述查询应该有效。