0

It took a while to come up with a title as I wasn't sure what to title it. Basically my problem deals with SQL queries and coming up with an efficient method to go about what I am trying to do.

To give it in an example, say we have two tables:

Table 1 (Articles): ID | ArticleName | AuthorID
Table 2 (Users):    ID | AuthorName

What I am attempting to do is pull, say the last 5 articles. From here, with each article it pulls it has a while loop to query the second table to pull AuthorName where ID=AuthorID.

In essence, we have one query for the 5 articles and then another five queries to get the author names. This is further compounded on pages with 10-20 or more articles, where there's an extra 10-20+ queries.

Is there a more efficient method to join these statements together and have it pull the AuthorName for each article it pulls?

The reason for using AuthorID in table 1 is so that if usernames are changed, it doesn't break anything. Along with this, it (as far as I understand) cuts down a lot on the database storage.

I'm still somewhat new to SQL though so any ideas on how to resolve this would be much appreciated.

Thanks in advance, and if there are any questions please don't hesitate to ask!

4

2 回答 2

2
SELECT * FROM `Articles` INNER JOIN `Users` ON `Articles`.`AuthorID`=`Users`.`ID`
于 2012-09-01T04:32:14.653 回答
0

There's two ways to do this. You can either do a one-shot query that JOINs in the additional authors table and presents a complete result set, or you can do a two pass where you fetch all the authors in a subsequent call using SELECT ... FROM Authors WHERE ID IN (...) using the distinct identifiers from the first query.

For small lists and small tables the JOIN method will almost always be more convenient. For large lists the two-pass approach seems "dumber" but often out-performs doing the join in the database. For instance, if the number of articles is very large and the number of authors is small then the JOIN adds significant amounts of work to the large query that could be eliminated by making a small secondary query after the fact.

For this case, with less than one million records and small fetch sizes, go with JOIN.

于 2012-09-01T04:50:28.010 回答