I need to combine various MySQL tables for a common result. The needed and expected result is a list of last X comments on a website but the tables are individuals, like: news_comments, pages_comments, etc. Individually, this tables has JOINS to users database.
The structure of 3 of this comments table are:
news_comments, pages_comments, other_comments
id int ai
id_new/id_page/id_other int
id_user int
comment text
created int (timestamp)
The table for users:
id int ai
login int
password varchar
...
I don't complete this last because we only need id and login.
The normal use of this queries (individuals) are:
SELECT users.id, users.login, news_comments.*, news_comments.id AS id_comment
FROM users, news_comments
WHERE users.id=news_comments.id_user AND news_comments.id_new=$id
ORDER BY created DESC
LIMIT $offset,$rows
And works fine!
But in the backend i want to have a list of all the comments on the website to moderate and control it. I need to combine all the comments tables, order it by created desc and limit the result to make a pagination.
I use MySQL and PHP, so if I need to use PHP there is no problem with that.开发者_运维技巧
How I can do it?
Thanks in advance!
SELECT *
FROM (
SELECT *
FROM (
SELECT *
FROM news_comments
WHERE id_new = $id
ORDER BY
created DESC
LIMIT $rows
) q
UNION ALL
SELECT *
FROM (
SELECT *
FROM pages_comments
WHERE id_new = $id
ORDER BY
created DESC
LIMIT $rows
) q
UNION ALL
SELECT *
FROM (
SELECT *
FROM other_comments
WHERE id_new = $id
ORDER BY
created DESC
LIMIT $rows
) q
) q
JOIN users u
ON u.id = q.id_user
ORDER BY
created DESC
LIMIT $offset, $rows
Note that limits are applied to each of the inner queries as well so that they could benefit from the indexes.
Create the following indexes:
CREATE INDEX ix_newscomments_new_created ON news_comments (id_new, created)
CREATE INDEX ix_pagescomments_new_created ON pages_comments (id_new, created)
CREATE INDEX ix_othercomments_new_created ON other_comments (id_new, created)
for this to work fast
精彩评论