我想选择使用两个表,其中一个表Data成为第二个表列

时间:2014-12-04 10:11:55

标签: sql

I have 2 tables . Like -
Table_A :
id   Locale_id   Text
 1    EN          TESTEN  
 2    ZH          TESTZH
 3    ES          TESTES
 4    EN          TESTEN_2
 5    ES          TESTES_2
 6    ZH          TESTZH_2
 7    CA          TESTEN 

Table_B :
id     EN           ES            ZH           CA
 1    TESTEN      TESTES        TESTZH       TESTEN
 2    TESTEN_2    TESTES_2      TESTZH_2

现在,我想根据文本的相似性从Table_A和Table_B中选择id。这可能吗?即使我想避免CA'在Select Query中重新出现 意味着结果如下:

选择Table_A.id为OLD_ID,Table_B.id为NEW_ID(这是这两列的来源),而Table_B中的id与Table_A id列没有任何关系。

OLD_ID  NEW_ID  TEXT
1       1       TESTEN
2       1       TESTZH
3       1       TESTES
4       2       TESTEN_2
5       2       TESTES_2
6       2       TESTZH_2

2 个答案:

答案 0 :(得分:1)

Table_A的设计比Table_B好得多。您可以轻松选择给定的语言(并且可以轻松添加语言)。要从Table_B获取每种语言的字符串,您需要在此处与UNION ALL粘合在一起的几个查询。

select a.id as old_id, b.id as new_id, a.text
from table_a a
join
(
  select id, 'EN' as locale_id, en as text from table_b
  union all
  select id, 'ES' as locale_id, es as text from table_b
  union all
  select id, 'ZH' as locale_id, zh as text from table_b
) b on b.locale_id = a.locale_id and b.text = a.text;

答案 1 :(得分:0)

The below query will you the result that you want:

SELECT A.id AS OLD_ID
        ,B.id AS NEW_ID
        ,B.[TEXT] 
FROM [Table A] AS A
INNER JOIN (SELECT Temp.id, 
        Temp.LOCALE_ID,
        Temp.[TEXT] 
        FROM [Table B]
        UNPIVOT ([TEXT] FOR LOCALE_ID IN (EN,ES,ZH,CA)) Temp) AS B 
ON A.[TEXT] = b.[TEXT]

If you want to exclude Locale_id of CA from the result set, please add the below where clause at end of the query.

WHERE B.locale_id NOT IN ('CA')