If commas then get substring, else return 整个字符串
If commas then get substring, else return whole string
如果 IF 存在 commas
或如果未找到 commas
则只返回整个字符串,我将如何提取?
例如:
640 => 640
310,321,450 => 310
1024,5,78, 900 => 1024
我正在考虑做这样的事情:(假设这个字符串在一个叫做 author_ids
的 table 行中)
[...]
WHERE SUBSTR(a.author_ids, 0, INSTR(a.author_ids, ',')) = b.author_id
OR a.author_ids = b.author_id
[...]
但这显然行不通。
谢谢。
附加信息:
大约有 10% 的 "author_ids" 有不止一位作者,因此 a.author_ids = b.author_id
可以正常工作,但有 ""
或 null
当超过一位作者。
这里有两种方法:
select substring_index(val, ',', 1)
或
select val + 0
第一个获取第一个逗号之前的所有内容。第二个将字符串转换为数字。忽略第一个非数字字符(例如“,”)之后的所有字符。
您似乎将数字列表存储在逗号分隔的字符串中。这是一个坏主意。您可能应该考虑使用联结 table 而不是将 numbers 存储为 strings 并在 string[= 中列出24=] 而不是 table.
SELECT CASE
WHEN author_ids LIKE '%,%'
THEN SUBSTRING_INDEX(author_ids, ',', 1)
ELSE author_ids
END AS author_ids
FROM yourtable
SQL FIDDLE: http://sqlfiddle.com/#!9/fca0e/3/0
如果 IF 存在 commas
或如果未找到 commas
则只返回整个字符串,我将如何提取?
例如:
640 => 640
310,321,450 => 310
1024,5,78, 900 => 1024
我正在考虑做这样的事情:(假设这个字符串在一个叫做 author_ids
的 table 行中)
[...]
WHERE SUBSTR(a.author_ids, 0, INSTR(a.author_ids, ',')) = b.author_id
OR a.author_ids = b.author_id
[...]
但这显然行不通。
谢谢。
附加信息:
大约有 10% 的 "author_ids" 有不止一位作者,因此 a.author_ids = b.author_id
可以正常工作,但有 ""
或 null
当超过一位作者。
这里有两种方法:
select substring_index(val, ',', 1)
或
select val + 0
第一个获取第一个逗号之前的所有内容。第二个将字符串转换为数字。忽略第一个非数字字符(例如“,”)之后的所有字符。
您似乎将数字列表存储在逗号分隔的字符串中。这是一个坏主意。您可能应该考虑使用联结 table 而不是将 numbers 存储为 strings 并在 string[= 中列出24=] 而不是 table.
SELECT CASE
WHEN author_ids LIKE '%,%'
THEN SUBSTRING_INDEX(author_ids, ',', 1)
ELSE author_ids
END AS author_ids
FROM yourtable
SQL FIDDLE: http://sqlfiddle.com/#!9/fca0e/3/0