同表同列不同条件查询

q9yhzks0  于 2021-06-17  发布在  Mysql
关注(0)|答案(5)|浏览(411)

我有这个表(url\u表):

+----+---------------+-------------+
| id | language_code |     url     |
+----+---------------+-------------+
| 60 | de            | german_url  |
| 60 | en            | english_url |
| 60 | fr            | france_url  |
| 60 | es            | spanish_url |
+----+---------------+-------------+

我想将这两个查询合并为一个:

SELECT url FROM url_table WHERE id = 60 AND language_code = 'de';
SELECT url FROM url_table WHERE id = 60 AND language_code = 'en';

结果应为德语和英语url,但重命名为url\u de和url\u en:

url_de: german_url
url_en: english_url
0kjbasz6

0kjbasz61#

你可以用 OR ```
SELECT url FROM url_table WHERE id = 60 AND language_code = 'de' OR language_code = 'en' ;

zfycwa2u

zfycwa2u2#

我认为您需要聚合或加入:

SELECT MAX(CASE WHEN language_code = 'de' THEN url END) as url_de,
       MAX(CASE WHEN language_code = 'en' THEN url END) as url_en      
FROM url_table
WHERE id = 60 AND language_code IN ('de', 'en')

这将适用于任意数量的 id 如果你使用 group by :

SELECT id,
       MAX(CASE WHEN language_code = 'de' THEN url END) as url_de,
       MAX(CASE WHEN language_code = 'en' THEN url END) as url_en      
FROM url_table
WHERE language_code IN ('de', 'en')
GROUP BY id;

也可以使用自联接:

select de.url as url_de, en.url as url_en
from url_table de join
     url_table en
     on de.id = en.id and
        de.language_code = 'de' and
        en.language_code = 'en'
where de.id = 60;

但是,如果两种语言都没有行,这就很棘手了,这就是为什么我推荐 group by 接近。

ergxz8rk

ergxz8rk3#

不确定语法是否完美,但可能是这样的。

SELECT 
  u.id 
, url_de = (SELECT URL FROM url_table u2 WHERE u2.ID = u.id AND u2.language_code ='de')
, url_en = (SELECT URL FROM url_table u2 WHERE u2.ID = u.id AND u2.language_code ='de')
FROM url_table u
WHERE u.id = 60
monwx1rj

monwx1rj4#

试试这个

SELECT concat('url_',language_code ,':  ',url) As url
 FROM url_table
 WHERE id = 60 AND (language_code = 'de' OR language_code = 'en');

输出:

8yoxcaq7

8yoxcaq75#

你可以试着用 in ```
SELECT url
FROM url_table
WHERE id = 60 AND language_code in ('de','en');

从你期望的结果你可以尝试使用 `concat` 功能。
查询#1

SELECT concat('url_',language_code ,':',url)
FROM url_table
WHERE id = 60 AND language_code in ('de','en');

concat('url_',language_code ,':',url)
url_de:german_url
url_en:english_url
db fiddle视图

相关问题