我有两列:表shipping中的amountFrom和amountTo
假设我有以下行数据:
amountFrom | amountTo
-----------------------
0 15
16 30
31 50现在我想补充这三点:
amountFrom | amountTo
-----------------------
15 22 (should fail, already exist (crosses range))
18 25 (should fail, already exist)
55 76 (should pass)我如何做一个正确的sql查询,它将为我想要插入的每一行运行,它将检查“范围”是否可用?
我尝试过的示例
SELECT id FROM shipping WHERE amountFrom >= 15 AND amountTo <= 22上面的查询不返回任何行,这是应该的(如果它是一个正确的查询),因为我们不想创建一个包含15和22的新行,因为它将跨越现有的权重范围
发布于 2014-02-03 02:37:10
您可以尝试这样(这里的值分别为15和22):
INSERT INTO t (amountFrom, amountTo)
SELECT 15, 22
WHERE NOT EXISTS (SELECT 1 FROM t WHERE 22 >= amountFrom AND 15 <= amountTo);您可以检查inserted rows值,以查看该行是否被实际插入。
发布于 2014-02-03 02:25:18
您不必执行三个单独的插入操作。您可以一次完成所有这些操作(至少使用查询中的数据)。
用于查看哪些不重叠的select语句为:
select t2.*
from table2 t2
where not exists (select 1
from table1 t1
where t1.amountFrom <= t2.amountTo and
t1.amountTo >= t2.amountFrom
);如果一个范围在另一个结束之前开始,并且第一个结束在另一个开始之后,则两个范围重叠。
将此代码放入insert中,作为
insert into t1(amountFrom, amountTo)
select t2.amountFrom, t2.amountTo
from table2 t2
where not exists (select 1
from table1 t1
where t1.amountFrom <= t2.amountTo and
t1.amountTo >= t2.amountFrom
);编辑:
如果您想一次一行地执行此操作,并防止新行中也有重叠:
insert into t1(amountFrom, amountTo)
select t2.amountFrom, t2.amountTo
from (select XX as amountfrom, YY as amountTo
) t2
where not exists (select 1
from table1 t1
where t1.amountFrom <= t2.amountTo and
t1.amountTo >= t2.amountFrom
);这将使用重叠逻辑一步一步地执行插入。
https://stackoverflow.com/questions/21514353
复制相似问题