Muh*_*aqi 9 sql postgresql pattern-matching sql-like
我在表格中有以下数据:
+----------------------+----------------------------------------------------------+--------------+
| subscriber_fields_id | name | field_type |
+----------------------+----------------------------------------------------------+--------------+
| 143 | Peshawar/Islamabad/Lahore/Swat/Mardan/Karachi | Job Location |
| 146 | Karachi | Job Location |
| 147 | Lahore and Karachi | Job Location |
| 149 | Karachi, Mirpur Khas, Sukkur, Layyah, Gilgit, Charsaddah | Job Location |
| 152 | Islamabad or Lahore | Job Location |
| 155 | Islamabad | Job Location |
| 157 | 7 Districts of Sindh and Karachi | Job Location |
+----------------------+----------------------------------------------------------+--------------+
Run Code Online (Sandbox Code Playgroud)
我的查询是:
select * from subscriberfields
where name like '%Khairpur,Islamabad,Karachi%';
Run Code Online (Sandbox Code Playgroud)
结果:
+----------------------+-----------------------------------------------+--------------+
| subscriber_fields_id | name | field_type |
+----------------------+-----------------------------------------------+--------------+
| 143 | Peshawar/Islamabad/Lahore/Swat/Mardan/Karachi | Job Location |
| 152 | Islamabad or Lahore | Job Location |
| 155 | Islamabad | Job Location |
+----------------------+-----------------------------------------------+--------------+
Run Code Online (Sandbox Code Playgroud)
它应该返回名称包括伊斯兰堡,Khairpur或卡拉奇的所有行,但事实并非如此.
Erw*_*ter 14
要获得正确的解决方案,请对数据库设计进行规范化,或者除此之外,请考虑全文搜索.
要快速解决当前问题,请使用正则表达式match(~)或三个简单LIKE表达式:
SELECT *
FROM subscriberfields
WHERE name ~ '(Khairpur|Islamabad|Karachi)';
Run Code Online (Sandbox Code Playgroud)
要么:
...
WHERE (name LIKE '%Khairpur%' OR
name LIKE '%Islamabad%' OR
name LIKE '%Karachi%')
Run Code Online (Sandbox Code Playgroud)
或者使用~*或ILIKE不区分大小写的匹配.
由于另一个答案建议:永远不要使用SIMILAR TO:
小智 5
你可以使用这个:
select * from subscriberfields
where name like any(array['%Khairpur%','%Islamabad%','%Karachi%']);
Run Code Online (Sandbox Code Playgroud)
https://postgres.cz/wiki/PostgreSQL_SQL_Tricks#LIKE_to_list_of_patterns
小智 -1
在 WHERE 子句中使用 OR,例如,
select * from subscriberfields where name like '%Khairpur%' OR name like '%Islamabad%' OR name like '%Karachi%';
Run Code Online (Sandbox Code Playgroud)
希望它有效。
| 归档时间: |
|
| 查看次数: |
13048 次 |
| 最近记录: |