dongli7236 2016-01-20 11:48
浏览 6

如何使用特定属性查询至少X个结果

I am trying to get a certain amount of rows of which another amount of rows satisfy a specific condition.

I'll explain.

table 1:

  ID     |   NAME
  1      |   Thomas
  2      |   Jason
  3      |   Oleg
  4      |   Matt
  5      |   Sheldon
  6      |   Jenny

table 2:

  ID     |   ACTIVE
  1      |   1
  2      |   0
  3      |   1
  4      |   1
  5      |   0
  6      |   1

Query:

SELECT tbl_1.ID, tbl_1.NAME, tbl_2.ACTIVE
FROM tbl_1  JOIN tbl_2 ON 
tbl_1.ID = tbl_2.ID  
WHERE tbl_2.ACTIVE=1 
LIMIT 5

in this example I would like to get a minimum number of 5 users, of which 3 are active. of course the query above will not do the job right, as it limits the total rows to 5. But 3 of the rows in the result (or less if no more exist) MUST be active.

the other way I can think of getting this done, is a union, but my query is so cumbersome, long and complex.

Any ideas?

  • 写回答

2条回答 默认 最新

  • dslfjrmz70457 2016-01-20 11:54
    关注

    Use ORDER BY instead:

    SELECT tbl_1.ID, tbl_1.NAME, tbl_2.ACTIVE
    FROM tbl_1 JOIN
         tbl_2 
         ON tbl_1.ID = tbl_2.ID  
    ORDER BY (tbl_2.ACTIVE = 1) DESC
    LIMIT 5;
    

    This puts the active users at the top of the list and then fills in the rest with other users.

    Note: The ORDER BY clause could simply be ORDER BY tbl_2.ACTIVE DESC. I left the boolean logic so you could see the similarity to the WHERE clause.

    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line