简体   繁体   中英

More efficient way to fetch data from MySQL

Suppose I have a MySQL table called "User" .

ID, Name, Email, Age, Gender, Country, Hometown, City, Address, Relationship_Status, Employment_Status, IP, Registered_Time

Now, which query is more efficient to fetch all info of a user?

A)

SELECT * FROM User WHERE id=1

B)

SELECT ID FROM User WHERE id=1

SELECT Name FROM User WHERE id=1

SELECT Email FROM User WHERE id=1

SELECT Age FROM User WHERE id=1

SELECT Gender FROM User WHERE id=1

SELECT Country FROM User WHERE id=1

SELECT Hometown FROM User WHERE id=1

SELECT City FROM User WHERE id=1

SELECT Address FROM User WHERE id=1

SELECT Relationship_Status FROM User WHERE id=1

SELECT Employment_Status FROM User WHERE id=1

SELECT IP FROM User WHERE id=1

SELECT Registered_Time FROM User WHERE id=1

Thing is, depending on situation , I may or may not need all of the data . So, should I just fetch each data one by one when I need them or should I fetch all the data at once and then use as I need?

Thanks for helping!

A single query fetching multiple columns is almost always more efficient than multiple queries. Why? The query must be serialized by php, sent to the mySQL server, deserialized. Then the mySQL server has to do the WHERE operation to find the appropriate row or rows. Finally it has to serialize the results and send them back to php. The less you do all this, the less work the system has to do.

Pro tip: Don't use SELECT * . Instead enumerate the columns you want, like so.

SELECT ID, Name, Email, Employment_Status, Registered_Time FROM Users WHERE ID = 1

There are a lot of advantages to that approach, especially in queries that return many rows (which yours does not).

Each query to database costs something. PHP has to send the query to SQL server, the query analyzer has to parse your query, optimize it, translate it into some internal code, lookup the table, seek in the index file on the disk, seek in the data file on the disk.

The cost of selecting all columns at once using SELECT * is almost the same as cost of selecting a single column individually in one sql query.

When the data is read from the file on disk, it won't read just the 10 bytes you need, data from disk is always read in much bigger chunks by the operating system (like 4KB, it may depend).

Selecting one column like "SELECT Age ..." will read from disk the entire row anyway in vast majority of cases.

So to answer your question, SELECT * in your example will be more efficient since you'll go through the overhead of parsing a query just once.

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