Performing a search... one large query or a medium and many small queries?
Right now the below query returns 1 row for each result.... I need to show a list of tags for each row and I'm debating whether to change this query so it INNER JOINS the tags and parsing out the data on the PHP end, or if I should just run a separate query for each return result.... what are your thoughts on this? Should I pull the extra data and parse it on the PHP end or run additional queries (maybe 25-30)?
SELECT
content.id,
content_text.content
FROM content
INNER JOIN content_text ON (
content_text.content_id = content.id AND
conte开发者_开发问答nt_text.language_id = 1
)
INNER JOIN tags_to_content ON (
tags_to_content.tag_id IN (1)
)
You could rely on a small command that is not used much in mysql : GROUP_CONCAT()
.
Official Doc for GROUP_CONCAT
Here is a small example (not based on your current question since I don't know the specifics, its a example that could apply to a blog):
SELECT
p.title as title,
p.content as content,
GROUP_CONCAT(c.name order by c.name SEPARATOR ', ') as categories
FROM
post as p
INNER JOIN
post_category as pc
ON
p.id = pc.post_id
INNER JOIN
category as c
ON
pc.category_id = c.id
GROUP BY
p.id
Which would return
+------------------+--------------------+------------------------------------+
| title | content | categories |
+------------------+--------------------+------------------------------------+
| Some title | Some content | category 1, category 2, category 3 |
| Some other title | Some other content | category 1, category 3, category 4 |
...
+------------------+--------------------+------------------------------------+
I always trade off the number of results to loop through vs the total number of rows, and the number of records in the joined tables.
Let's say you have 1000 records in your table "students", and all students fall in 3 categories (categorie_id left join categories on... ), I'd loop through the students and fetch (+ cache) the joined table (categories).
If you have 1000 students, and 1500 parents (parent_id from table parents), and your result for your query (eg "students outside of this city") returns all students, I'd go for the joined-tables. If you only expect 10% of the students to be returned (eg "students outside of the city"), I'd again go for small queries (like the first example).
If in doubt, run an example query and put a timer on it ... ?
精彩评论