代码之家  ›  专栏  ›  技术社区  ›  jonny

在顶部显示并标记一些记录

  •  0
  • jonny  · 技术社区  · 14 年前

    我的目标DBMS是Oracle和MySQL

     SELECT
      users.*
      , hr_orders.position_label
      , hr_orders.is_boss
      , deps.label AS dep_label        -- preprocessor removes AS when using Oracle
      , users.id IN (?) AS show_on_top -- Oracle doesn't accept this IN thing
     FROM
      -- some joins here
     WHERE
      -- some filters
    

    更新

    WHERE
        users.fake = 0
    AND (
            users.id IN (?)
        OR
            -- some more detailed filters
        )
    ORDER BY
        IF (users.id IN (?), 1, 2), users.label
    

    此show\u on\u top字段需要在以后突出显示顶级记录。

    因此,如果我移到where子句中,将只选择显示在顶部的用户,而不选择其余的用户。

    将查询一分为二并在代码中组合用户列表在我看来仍然很难看。

    4 回复  |  直到 11 年前
        1
  •  1
  •   Thilo    14 年前

    SELECT
      users.*
      , hr_orders.position_label
      , hr_orders.is_boss
      , deps.label AS dep_label        
      , users.id  AS show_on_top 
     FROM
      -- some joins here
     WHERE
      -- some filters
      AND users.id IN (?,?,?)
    
        2
  •  1
  •   user180100 user180100    14 年前

    这应该起作用:

    WHERE users.id IN (?) AND 
      -- some filters
    
        3
  •  0
  •   spbfox    14 年前

    在我看来,这个查询对mysql也不起作用。只能在查询的“WHERE”部分使用“IN”。在您的示例中,它位于字段列表中。你能提供完整的查询而没有你的评论吗?

        4
  •  0
  •   Gary Myers    14 年前

    如果您希望这些行位于顶部,而不仅仅是这些行,您只需要将它们按顺序排列,而不是按WHERE(或SELECT)排列。

    ORDER BY
        CASE WHEN users.id IN (?) then 1 else 2 end, users.label