SQL Using Between for two tables

旧城冷巷雨未停 提交于 2020-02-25 04:25:10

问题


Hi I want to fetch data from a Table based on values that lie between two columns of another table, below SQL shoulde explain my purpose:

SELECT * FROM TABLE 1 WHERE 1.FIELD1 BETWEEN 
(SELECT 2.RANGE_FROM FROM TABLE 2) AND (SELECT 2.RANGE_TO FROM TABLE 2)

This is not working as I am getting error:

Error: SQL0811N  The result of a scalar fullselect, SELECT INTO statement, or VALUES INTO statement is more than one row.  SQLSTATE=21000
 (State:21000, Native Code: FFFFFCD5)

This is obvious as both the subqueries return multiple rows. So I want to write a SQL to perform above function without error. The platform is IBM DB2.

EDIT:

Ok I think I solved this one by joining 2 tables using the condition:

SELECT * FROM TABLE1 A, TABLE2 B WHERE A.FIELD1 BETWEEN B.RANGE_FROM AND B.RANGE_TO

More testing is required though.


回答1:


I suspect you want to check if the table1 column values are between the 2 columns of (some row of) table2:

SELECT a.* 
FROM TABLE1 AS a 
WHERE EXISTS 
      ( SELECT 1
        FROM TABLE2 AS b 
        WHERE a.FIELD1 BETWEEN b.RANGE_FROM AND b.RANGE_TO
      ) ;

This way, you'll have no duplicates from table1, so there is no need for DISTINCT.

Also note that the condition:

a.FIELD1 BETWEEN b.RANGE_FROM AND b.RANGE_TO

is equivalent to:

b.RANGE_FROM <= a.FIELD1  AND  a.FIELD1 <= b.RANGE_TO



回答2:


The values used in between clause should be scalar values. As your sub queries are returning multiple rows, therefore the query is failing. Try refining your sub queries to return just one result. For this first decide what value of range_from and range_to from table2 should your field lie in between of. Try min of range_from and max of range_to, or apply where caluse in your subquery depending on your requirement.



来源:https://stackoverflow.com/questions/12706638/sql-using-between-for-two-tables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!