代码之家  ›  专栏  ›  技术社区  ›  Rasoul Taheri

如何进行基于类别的选择查询条件

  •  0
  • Rasoul Taheri  · 技术社区  · 6 年前

    我有这样的桌子

    id  category  minLimit  maxLimit  count  
    11  Bannana     100       200      50
    12  Bannana     200       300      20  
    13  Bannana     300       400      40  
    14  Apple       100       200      60  
    15  Apple       200       300      70  
    

    现在我将执行查询a query并返回bannana by limit 250和apple by limit 150。 在这种情况下,我可以这样运行Q查询:

    select  
       * 
    from main_table 
    where 
       (category = 'Bannana' and minLimit <= 250 and maxLimit > 250) or 
       (category = 'Apple' and minLimit <= 150 and maxLimit > 150)
    

    在另一个解决方案中,我可以创建一个额外的表插入where子句条件(bannana 250,apple 150)数据并与main_表进行连接。我想知道什么是最有效的解决方案?

    注:我的where条款条件(bannana-250,apple 150)在实际情况下超过5000条记录

    1 回复  |  直到 6 年前
        1
  •  1
  •   Caius Jard    6 年前

    不,没有比请求数据库执行它构建的任务更有效的方法来实现您的请求:连接数据。将5000条记录插入另一个表,然后执行以下操作:

    create table conditions_table(category VARCHAR(20), limit INT);
    insert into conditions_table('Bannana', 250);
    insert into conditions_table('Apple', 150);
    

    然后:

    select  
       * 
    from 
      main_table m
      INNER JOIN 
      conditions_table c --could be temp table, real table, table var etc
      ON
       c.category = m.category and
       c.limit >= m.minLimit and
       c.limit < m.maxlimit