What is the best way to select multiple rows by ID in sql?

后端 未结 5 1199
南方客
南方客 2021-02-03 23:37

I need to select multiple records

I use

SELECT *
FROM `table`
WHERE `ID` =5623
   OR `ID` =5625
   OR `ID` =5628
   OR `ID` =5621

this

相关标签:
5条回答
  • 2021-02-03 23:56
    SELECT *
    FROM `table`
    WHERE `ID` in (5623, 5625, 5628, 5621)
    

    While Researching this further I came across an interesting blog post that explains how to use a set to get faster SQL performance from In clauses, by creating list of ids into a Common Table Expression (CTE) and then joining on that.

    So you could code the PHP equivalent of the following to get maximum performance.

    DECLARE  @idList varchar(256) 
    SET @idList = '5623, 5625, 5628, 5621'
    
    ;with ids (id) as
    (
        SELECT value FROM UTILfn_Split(@idList,',')
    )
    
    SELECT     t.* 
    FROM     table as t
    INNER JOIN    ids
    ON        t.ID = ids.id
    
    0 讨论(0)
  • 2021-02-03 23:57

    On top of what the people stated (where id in):

    1) iF there are a lot of IDs, better to stick them into a temp table and run a join with that temp table

    2) Make sure your table has an index on id

    3) If the real-timeliness of the data is not critical, put the query results in a cache on the application side

    0 讨论(0)
  • 2021-02-04 00:03
    SELECT *
    FROM `table`
    WHERE `ID` IN (5623, 5625, 5628, 5621)
    

    But four times per second is a lot. I would think about another approach that needs less database access.

    0 讨论(0)
  • 2021-02-04 00:04
    SELECT *
    FROM `table`
    where ID in (5263, 5625, 5628, 5621) 
    

    is probably better, but not faster.

    0 讨论(0)
  • 2021-02-04 00:08

    If you do

    SELECT *
    FROM `table`
    WHERE `ID` IN (5623, 5625, 5628, 5621)
    

    You should be fine, as long as the number of ID's don't get too big. I'd suggest you create an index for the ID's, so the query will perform faster.

    Also, consider changing your logic, so you don't have to pass that many ID's

    0 讨论(0)
提交回复
热议问题