在同一表的同一列中以不同条件查询

时间:2018-12-11 15:19:52

标签: mysql sql select conditional-statements where

我有这张桌子(url_table):

tell application "System Events" to set name of file "Volumes:Projects:Projects:1.pdf" to "2.pdf"

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

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

结果应为德语和英语url,但重命名为url_de和url_en:

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

5 个答案:

答案 0 :(得分:2)

您可以尝试使用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                    |

View on DB Fiddle

答案 1 :(得分:0)

您可以使用OR

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

答案 2 :(得分:0)

不确定语法是否完美,但也许像这样。

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

答案 3 :(得分:0)

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

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方法的原因。

答案 4 :(得分:0)

尝试

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

输出:

enter image description here