我在MySQl表中有以下行示例
Column A
Row1 Lauguage=English&Country=USA&Gender=Male
Row2 Gender=Female&Language=French&Country=
Row3 Country=Canada&Gender=&Language=English
如何实现以下目标:例如,我需要查找国家/地区
结束结果:新列
Column B
Row1 USA
Row2
Row3 Canada
任何帮助都将不胜感激!谢谢!
答案 0 :(得分:7)
您可以选择'Country ='后的文字,然后一旦有了子字符串,请在第一个'&'之前选择文字
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(ColumnA, 'Country=', -1), '&', 1) AS ColumnB
FROM `atable`
请参阅http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_substring-index
这是一个测试来证明:
mysql> SELECT * FROM atable;
+------+------------------------------------------+
| row | columna |
+------+------------------------------------------+
| Row1 | Lauguage=English&Country=USA&Gender=Male |
| Row2 | Gender=Female&Language=French&Country= |
| Row3 | Country=Canada&Gender=&Language=English |
+------+------------------------------------------+
mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(ColumnA, 'Country=', -1), '&', 1) AS ColumnB FROM atable;
+---------+
| ColumnB |
+---------+
| USA |
| |
| Canada |
+---------+
重新提出你的后续问题:
INSERT INTO atable VALUES ('Row4', 'Gender=&Language=English');
SELECT `row`, IF(LOCATE('Country=', ColumnA)>0,
COALESCE(
NULLIF(SUBSTRING_INDEX(SUBSTRING_INDEX(ColumnA, 'Country=', -1), '&', 1), ''),
'Blank string is not valid!'),
'Missing Country!') AS ColumnB
FROM `atable`
+------+----------------------------+
| row | ColumnB |
+------+----------------------------+
| Row1 | USA |
| Row2 | Blank string is not valid! |
| Row3 | Canada |
| Row4 | Missing Country! |
+------+----------------------------+
答案 1 :(得分:0)
但是我有完全相同的问题,在SQL中,对于任何想要SQL答案的人,请参见Tim Biegeleisen评论here
create table elb_logs(row varchar(100), url varchar(100));
insert into elb_logs values("Row1", "Lauguage=English&Country=USA&Gender=Male");
SELECT
row,
CASE WHEN POSITION('Country=' IN url) > 0
THEN SPLIT_PART(SPLIT_PART(url, 'Country=', 2), '&', 1)
ELSE 'Missing Country!' END AS ColumnB
FROM elb_logs;