【问题标题】:Avoid crossing weight range BETWEEN, with two columns? mysql避免在两列之间跨越重量范围? mysql
【发布时间】:2014-02-26 04:06:48
【问题描述】:

我有两列:amountFromamountTo 在表 shipping

假设我有这些行数据:

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 创建一个新行,因为它会跨越现有的权重范围

【问题讨论】:

标签: php mysql sql


【解决方案1】:

你可以试试这个(这里的值是 15 和 22):

INSERT INTO t (amountFrom, amountTo)
 SELECT 15, 22
 WHERE NOT EXISTS (SELECT 1 FROM t WHERE 22 >= amountFrom AND 15 <= amountTo);

您可以检查affected-rows 值以查看该行是否实际插入。

【讨论】:

    【解决方案2】:

    您不必执行三个单独的插入操作。您可以一次完成所有操作(至少使用查询中的数据)。

    查看哪些不重叠的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 as

    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
                         );
    

    这将使用重叠逻辑一次插入一个步骤。

    【讨论】:

    • 你在做什么?只有一张桌子。
    • @KarolyHorvath 。 . .我假设要在 OP 中以表格格式插入的三行实际上是第二个表格。
    • 你可能错了。无论如何..我认为这假设第二个表中没有重叠。
    • @KarolyHorvath 。 . .我同意(这就是我所说的为问题中的数据工作的意思)。没有“失败,作为新行存在”的例子。
    • 戈登只有一张桌子?
    猜你喜欢
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 2022-08-13
    相关资源
    最近更新 更多