带有子查询的SQL查询表,范围从第二个表开始

时间:2017-12-02 00:56:58

标签: mysql sql sql-server sqlite

我有两个表,表一有两个范围用于查询第二个表,我想在单个查询中执行此操作到目前为止我有两个单独的查询但似乎无法找到如何一起使用它们

This is table one, with the ranges that are from_book_id, from_chapter, to_book_id and to_chapter.

这是我用来获取所需行的查询:

SELECT * FROM plans WHERE plans.day = 1 AND plans.plan_id  = 1

This is the second table with the data to filter with tables one range.

我用它来从这张表中获得所需的结果

SELECT verse.* FROM verse WHERE (verse.book_id >= 1 AND verse.book_id <= 1) AND (verse.chapter >= 1 AND verse.chapter <= 5))

为了澄清,我需要使用第一个表中的结果范围作为第二个表的查询,如下所示:

SELECT t1.* FROM t1 WHERE (t1.book_id >= t2.from_book_id AND t1.book_id <= t2.to_book_id) AND (t1.chapter >= t2.from_chapter AND t1.chapter <= t2.to_chapter))

我希望这个解释很清楚,我提前感谢你们。

修改

我似乎在查询中遇到了一些特殊情况,尽管当我遇到以下范围时它完全正常:

from_book_id:1, from_chapter:1, to_book_id:1, to_chapter:5

该范围会返回所需的结果,但当范围从一本书变为另一本时,如下所示:

from_book_id:1, from_chapter:5, to_book_id:2, to_chapter:5

这意味着它需要从第1册第5章到第1册的最后一章获得所有内容,并继续第2册到第5章。

这些情况会破坏查询并返回null,如果你能帮我解决这个问题我真的很感激。

再次感谢!

2 个答案:

答案 0 :(得分:2)

尝试这个:希望它能为您提供您想要的确切输出。它将根据verse表条件

查询plans表数据
SELECT * --you can shorten the columns by defining the required column names
FROM plans p
INNER JOIN verse v ON v.book_id BETWEEN p.from_book_id AND p.to_book_id
    AND v.chapter BETWEEN p.from_chapter AND p.to_chapter
WHERE p.day = 1 AND p.plan_id  = 1

更新要求:我们可以使用UNION

SELECT * --you can shorten the columns by defining the required column names
FROM plans p
INNER JOIN verse v ON v.book_id = p.from_book_id
    AND v.chapter >= p.from_chapter
WHERE p.day = 1 AND p.plan_id  = 1
UNION
SELECT * 
FROM plans p
INNER JOIN verse v ON v.book_id = p.to_book_id
    AND v.chapter <= p.to_chapter
WHERE p.day = 1 AND p.plan_id  = 1

答案 1 :(得分:0)

您可以使用cortition连接类型来获得结果

请尝试下面的内容,希望这有帮助。

select a.* 
FROM  verse a
    , plans b 
where 
     a.book_id between  b.From_book_id and b.to_book_id
and  a.chapter between b.from_chapter and b.to_chapter