开发者

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

开发者 https://www.devze.com 2022-12-22 02:07 出处:网络
I need to select multiple records I use SELECT * FROM `table` WHERE `ID` =5623 OR `ID` =5625 OR `ID` =5628

I need to select multiple records

I use

SELECT *
FROM `table`
WHERE `ID` =5623
   OR `ID` =5625
   OR `ID` =5628
   开发者_运维百科OR `ID` =5621

this query runs 4 times per second with php

is there a better and faster way for this ?


SELECT *
FROM `table`
where ID in (5263, 5625, 5628, 5621) 

is probably better, but not faster.


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


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号