Fetch Data from table 1 based on text in a column and a different text in a column of different table

Fetch Data from table 1 based on text in a column and a different text in a column of different table

我有两张桌子。

Table 1:

T1id1(pk) col1 col2 col3

Table 2:

id(pk) T1id1(FK) col1 col2 col3

我从用户那里得到两条文本,其中 table1.col1 有一些文本(如 %text1%),同样对于 table2 col1,我得到另一个不等于 text1 的文本(如 %text2%)。

我需要从 table1 中获取一组一百条记录,其中 table2 col1 包含 text2 AND Table1 col1 包含 text1。当查询下一组 100 条记录时,我不应该得到第一组 100 条记录中的任何记录。

下面是我编写的示例查询,但它失败了。我正在使用 Apache Phoenix,任何 SQL 兼容数据库中的解决方案都很好。

SELECT * FROM table1 WHERE T1id1 IN (select T1id1 from ndm.table1 where
T1id1 NOT IN( select T1id1 from table1 where T1id1 in (select distinct
T1id1(FK) from table2 WHERE table2.col1 like '%text2%' )LIMIT     100)     AND T1id1 in (select distinct T1id1(FK) from table2 WHERE     
table2.col1 like '%text2%' limit 200) and table1.col1 ilike '%text2%' LIMIT 100);

鉴于您使用 ILIKE,您可能尝试过使用 PostgreSQL - 它似乎允许在单个语句中使用多个 LIMIT。 (据此 SQL Fiddle 判断,其中 - 与您的陈述相比 - ndm.table1 已更改为 table1,并且 (FK) 掉了两次).

但即使调整后

SELECT
  *
FROM table1
WHERE
  T1id1 IN
    (select
       T1id1
     from table1
     where
       T1id1 NOT IN
         (select T1id1
          from table1
          where
            T1id1 in
              (select distinct
                 T1id1
               from table2
               WHERE
                 table2.col1 like '%text2%'
              )
          LIMIT 100
         )
     AND T1id1 in
       (select distinct
          T1id1
        from table2
        WHERE
          table2.col1 like '%text2%'
        limit 200
       )
     and
     table1.col1 ilike '%text2%'
     LIMIT 100
    )
;

似乎被 Postgre 接受SQL - 它不太可能 return 预期的结果:

When using LIMIT, it is important to use an ORDER BY clause that constrains the result rows into a unique order. Otherwise you will get an unpredictable subset of the query's rows. You might be asking for the tenth through twentieth rows, but tenth through twentieth in what ordering? The ordering is unknown, unless you specified ORDER BY.

来自 PostgreSQL 9.3 文档 7.6 LIMIT and OFFSET.

从头开始,只是根据您的问题描述(并查看您陈述中的一些细节),类似于

SELECT
  T1.*
FROM Table1 T1
JOIN Table2 T2
  ON T1.t1id1 = T2.t1id1
  AND INSTR(T1.col1, 'teXT1')
  AND INSTR(T2.col1, 'teXT2')
ORDER BY T1.t1id1, T2.id
LIMIT 1 OFFSET 0
;

SELECT
  T1.*
FROM Table1 T1
JOIN Table2 T2
  ON T1.t1id1 = T2.t1id1
  AND INSTR(T1.col1, 'teXT1')
  AND INSTR(T2.col1, 'teXT2')
ORDER BY T1.t1id1, T2.id
LIMIT 1 OFFSET 1
;

SELECT DISTINCT
  T1.*
FROM Table1 T1
JOIN Table2 T2
  ON T1.t1id1 = T2.t1id1
  AND INSTR(T1.col1, 'teXT1')
  AND INSTR(T2.col1, 'teXT2')
ORDER BY T1.t1id1, T2.id
LIMIT 1 OFFSET 0
;

应该会让你进入正确的方向。您是否需要 DISTINCT 在某种程度上取决于您的数据 - 但更重要的是取决于您的总体要求。请比较下面 SQL Fiddle 中的陈述 1 到 4 和 5 到 7,以了解效果。

主要是将 LIMITOFFSET 结合起来 - 您似乎已尝试找到自己的替代品。

除此之外:由于通配符位于字符串的两端,INSTR 具有与 LIKE 相同的选择性 - 但在某些情况下效率更高...

记住您对 ILIKE 的使用:只要比较中不涉及二进制字符串,LIKEINSTR 在 MySQL 中都不区分大小写。

查看实际效果:SQL Fiddle

如果需要调整/进一步的详细信息,请发表评论。