简体   繁体   English

oracle查询以使用IN运算符选择值

[英]oracle query to select values using IN operator

I have a string which has list of valid places. 我有一个包含有效地点清单的字符串。

var locations = COLOMBO,DELHI,SINGAPORE

I want to query all the employees belonging to the location mention in the above string 我想查询上述字符串中提及的所有属于该位置的员工

I am using the following query 我正在使用以下查询

SELECT emp_id,emp_name 
FROM EMPLOYEE 
WHERE emp_location IN (locations) ;

Oracle is considering it as single string and searching for the below query string Oracle正在将其视为单个字符串,并搜索以下查询字符串

SELECT emp_id,emp_name 
FROM EMPLOYEE 
WHERE emp_location IN ('COLOMBO,DELHI,SINGAPORE');

I want to know if there is any way I can pass the string and get the valid emp_id , emp_name belonging to the location mentioned in the string. 我想知道是否可以通过任何方式传递字符串并获得属于字符串中提到的位置的有效emp_idemp_name

As mentioned here 正如这里提到的

First you need to use the REGEXP_SUBSTR function to split the string into individual strings 首先,您需要使用REGEXP_SUBSTR函数将字符串拆分为单个字符串

VAR locations = 'COLOMBO,DELHI,SINGAPORE';

SELECT REGEXP_SUBSTR(locations,'[^,]+', 1, level) 
FROM dual
CONNECT BY REGEXP_SUBSTR(locations, '[^,]+', 1, level) IS NOT NULL;

Then use it as a sub query in a select to get the desired result 然后将其用作选择中的子查询以获得所需的结果

VAR locations = 'COLOMBO,DELHI,SINGAPORE';

SELECT emp_id,emp_name FROM EMPLOYEE 
WHERE emp_location in(
SELECT REGEXP_SUBSTR(locations,'[^,]+', 1, level) FROM dual
CONNECT BY REGEXP_SUBSTR(locations, '[^,]+', 1, level) IS NOT NULL);

You are looking for locations mentioned in the string, so actually for locations that are a substring of your string. 您正在寻找字符串中提到的位置,因此实际上是在寻找作为字符串子字符串的位置。 Oracle offers INSTR for such a search. Oracle为这种搜索提供了INSTR。

Only be aware to look for complete cities from comma to comma (add commas in front and end). 仅注意查找从逗号到逗号的完整城市(在开头和结尾添加逗号)。 So not to find 'YORK' in 'LONDON,NEW YORK' (for ',YORK,' is not a substring of ',LONDON,NEW YORK,' wheras 'YORK' without commas would be a substring of 'LONDON,NEW YORK'). 因此,不要在“ LONDON,NEW YORK”中找到“ YORK”(因为“,YORK”不是“,LONDON,NEW YORK”的子串,没有逗号的“ YORK”将是“ LONDON,NEW YORK”的子串“)。

select emp_id,emp_name 
from EMPLOYEE 
where instr(','|| locations || ',' , ',' || emp_location || ',') > 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM