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

后端 未结 5 1197
南方客
南方客 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
    

提交回复
热议问题