MySQL:如何从集合中删除行?

时间:2012-01-22 10:36:44

标签: mysql join group-by

我有翻译请求: (表结构:

  1. line_id
  2. lang(“en”或“ru”)
  3. 文本
  4. 所以,在表格中看起来像:

    5 | en | Test
    6 | en | Hello!
    7 | en | Another words
    6 | ru | Привет!
    

    并且所有翻译都与关键字line_id在同一个表中,该语言与语言无关)

    SELECT txt.line_id, txt.text AS o, ru.text AS t 
      FROM text AS txt, text AS ru 
     WHERE txt.line_id = ru.line_id 
       AND txt.lang = 'en';
    

    它会返回这样的数组

    > [5] => Array ( [line_id] => 5 [o] => Test [t] => Test 
    > [6] => Array ( [line_id] => 6 [o] => Hello! [t] => Hello! ) 
    > [7] => Array ( [line_id] => 6 [o] => Hello! [t] => Привет! )
    

    o - 是原始文本,t - 翻译。

    如何从第6行删除,因为我们在下一行中有翻译。 GROUP BY会杀掉#7并保存#6行。

    最好的结果是:

    > [5] => Array ( [line_id] => 5 [o] => Test [t] => ) 
    > [6] => Array ( [line_id] => 6 [o] => Hello! [t] => Привет! )
    

    没有[o] =>你好! [t] =>您好!

4 个答案:

答案 0 :(得分:3)

我猜你可能需要:

SELECT txt.line_id, 
         txt.text AS o, 
         COALESCE (ru.text,'UNTRANSLATED') AS t 
FROM 
  text AS txt
LEFT JOIN 
  text AS ru 
ON txt.line_id=ru.line_id AND ru.lang='ru'
WHERE txt.lang='en'

答案 1 :(得分:0)

从翻译表中排除原始语言

SELECT txt.line_id, txt.text AS o, ru.text AS t 
FROM text AS txt, text AS ru 
WHERE txt.line_id=ru.line_id 
   AND txt.lang='en' 
   AND ru.lang!='en'

新版本的新版本

SELECT txt.line_id, ru.lang, ru.text AS t 
FROM text AS txt, text AS ru 
WHERE txt.line_id=ru.line_id 
   AND txt.lang='en'
ORDER BY text.lang, txt.line_id

答案 2 :(得分:0)

如何按lang desc排序(所以ru在顶部),然后按line_id分组?

答案 3 :(得分:0)

为了列出没有翻译的翻译行和原始行,您必须面对MySql中缺少对访问同一个表的子查询的支持。

在我看来,你可以分解问题:首先列出没有翻译的原始行和一个SELECT;然后用另一个SELECT列出翻译;最后使用UNION。

-- original without translations
SELECT txt.line_id, txt.text AS o, ru.text AS t 
FROM text AS txt LEFT JOIN text AS ru 
ON(txt.line_id = ru.line_id AND txt.lang = 'en' AND ru.lang != 'en')
WHERE ru.line_id IS NULL -- ensures no translations have been found

UNION

-- only matching translations
SELECT txt.line_id, txt.text AS o, ru.text AS t
FROM text AS txt JOIN text AS ru 
ON(txt.line_id = ru.line_id AND txt.lang = 'en' AND ru.lang != 'en');

最好的问候。