开发者

Are database queries for everyone in a user list too much?

I am currently using MySQL and MyISAM.

I have a function of which returns an array of user IDs of either friends or users in general in my application, and when displaying them a foreach seemed best.

Now my issue is that I only have the IDs, so I would need to nest a database call to get each user's other info (i.e. name, avatar, other fields) based on the user ID in the loop.

I do not expect hundreds of thousands of users (mainly for hobby learning), although how should I do this one, such as the flexibi开发者_如何学Golity of placing code in a foreach for display, but not relying on ID arrays so I am out of luck to using a single query?

Any general structures or tips on what I can display the list appropriately with?

Is my amount of queries (1:1 per users in list) inappropriate? (although pages 0..n of users, 10 at a time make it seem not as bad I just realize.)


You could use the IN() MySQL method, i.e.

SELECT username,email,etc FROM user_table WHERE userid IN (1,15,36,105)

That will return all rows where the userid matches those ID's. It gets less efficient the more ID's you add but the 10 or so you mention should be just fine.


Why couldn't you just use a left join to get all the data in 1 shot? It sounds like you are getting a list, but then you only need to get all of a single user's info. Is that right?

Remember databases are about result SETS and while generally you can return just a single row if you need it, you almost never have to get a single row then go back for more info.

For instance a list of friends might be held in a text column on a user's entry.


Whether you expect to have a small database or large database, I would consider using the InnoDB engine rather than MyISAM. It does have a little higher overhead for processing than MyISAM, however you get all the added benefits (as your hobby grows) including JOIN, which will allow you to pull in specific data from multiple tables:

SELECT u.`id`, p.`name`, p.`avatar`
  FROM `Users` AS u
  LEFT JOIN `Profiles` AS p USING `id`

Would return id from Users and name and avatar from Profiles (where id of both tables match)

There are numerous resources online talking about database normalization, you might enjoy: http://www.devshed.com/c/a/MySQL/An-Introduction-to-Database-Normalization/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜