简体   繁体   中英

PHP PDO mysql fetch row by result id

I have a kind of odd question. Let's say I have an array of numbers like this:

$positions = array(1, 2, 5, 9, 25, 68, 130);

then I run a database query on a table with lets say 300 records

$stmt = dbpdo::$conn->query("SELECT * FROM table"); // 300 rows/records

Is there a way I can only fetch certain rows (results) based on my positions array? For example

$stmt->fetch(row #1);
$stmt->fetch(row #9);
$stmt->fetch(row #68);

You want to write your query to minimize the amount of data returned. Something like:

SELECT *
FROM table
WHERE id IN (1, 2, 5, 9, 25, 68, 130)

Otherwise the database is going to want to send you 100% of all data in the table on every request rather than just the 7 rows you're interested in.

You can also use LIMIT 1,$offset to get a single record $offset rows from the beginning of the result set. However, this is far less efficient. MySQL still computes 100% of the result set and then simply iterates through it until it gets to the Nth record.

Ideally, you also want to restrict your query to only return a finite set of columns rather than * . This will reduce the overhead of your application.

edit

In response to @serg's suggestion. ORDER BY RAND() is literally the devil. You should never use it unless you are 1,000,000% certain that your entire result set [ disregarding LIMIT clauses, LIMIT has no effect on how bad this is!] will never be larger than a few dozen rows and you're fine with completely throwing away all of your indexes.

Seriously, do not do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM