我有一个看起来像
的数据库 Alex,Anna,Peter
Alex
Alex,Peter
Alfons
Algebra,Geometry
Algebra,Physics
但是我只对逗号前的第一个表达式感兴趣。意思是我完美的答案是:
Alex
Alex
Alex
Alfons
Algebra
Algebra
到目前为止,我找到了SPLIT函数,但它仍然返回了一堆我真正不感兴趣的值。如何让它高效运行?
由于
答案 0 :(得分:2)
SELECT first(split(s,','))
FROM
(SELECT 'Alex,Anna,Peter' AS s),
(SELECT 'Algebra,Geometry' AS s);
输出:
Alex
Algebra
答案 1 :(得分:0)
SPLIT可能很昂贵,因为它将字符串转换为重复字段,因此这里有两个替代解决方案:
SELECT IFNULL(LEFT(s, INSTR(s, ',') - 1), s)
FROM
(SELECT 'Alex,Anna,Peter' AS s),
(SELECT 'Algebra,Geometry' AS s),
(SELECT 'Alfons' AS s)
和
SELECT REGEXP_EXTRACT(s, r'([^,]*)')
FROM
(SELECT 'Alex,Anna,Peter' AS s),
(SELECT 'Algebra,Geometry' AS s),
(SELECT 'Alfons' AS s)