如果有两种语言,MySQL会从表中选择一个值

时间:2017-12-20 22:18:26

标签: mysql sql

数据库中的两种语言:(英语和意大利语)

word_id  word      language
1        day       eng
2        mister    eng
3        cat       eng
4        paper     eng
1        giorno    ita
2        signor    ita
3        gatto     ita

我需要选择所有单词:如果单词存在则为意大利语单词,如果不存在则为英语单词。总之,它应该是四个字(3 ita + 1 eng)

2 个答案:

答案 0 :(得分:1)

这可以让你得到你想要的东西:

SELECT DISTINCT 
    w1.word_id
    , Word = COALESCE(w2.word, w3.word)
    , [Language] = COALESCE(w2.[Language] , w3.[Language] )
FROM words w1
LEFT JOIN words w2 ON w2.word_id = w1.word_id AND w2.[Language]  = 'ita'
LEFT JOIN words w3 ON w3.word_id = w1.word_id AND w3.[Language]  = 'eng'

答案 1 :(得分:0)

SQL中的注释给出了解释。 Union all将具有相同数量的列的2个结果集粘合在一起。

CREATE TABLE Table1        (`word_id` int, `word` varchar(6), `language` varchar(3));

INSERT INTO Table1
    (`word_id`, `word`, `language`)
VALUES
    (1, 'day', 'eng'),        (2, 'mister', 'eng'),        (3, 'cat', 'eng'),
    (4, 'paper', 'eng'),
    (1, 'giorno', 'ita'),     (2, 'signor', 'ita'),        (3, 'gatto', 'ita')

查询:

 ( -- this selects all the italian words
    select word 
    from Table1
    where language = 'ita'  
  )
  union all
  ( -- this selects all words with ids that are not in the ita, if you have a 
    -- third language they would be selected as well
      select word
      from Table1 engWrd
      where not exists ( -- this ensures same id is not given by 'ita'
          select 1 
          from Table1 
          where engWrd.word_id = word_id 
          and language = 'ita'
      ) 
  )

结果:

word
giorno
signor
gatto
paper