Best way to combine multiple advanced mysql select queries

送分小仙女□ 提交于 2019-12-12 16:55:06

问题


I have multiple select statements from different tables on the same database. I was using multiple, separate queries then loading to my array and sorting (again, after ordering in query).

I would like to combine into one statement to speed up results and make it easier to "load more" (see bottom).

Each query uses SELECT, LEFT JOIN, WHERE and ORDER BY commands which are not the same for each table.

I may not need order by in each statement, but I want the end result, ultimately, to be ordered by a field representing a time (not necessarily the same field name across all tables).

I would want to limit total query results to a number, in my case 100.

I then use a loop through results and for each row I test if OBJECTNAME_ID (ie; comment_id, event_id, upload_id) isset then LOAD_WHATEVER_OBJECT which takes the row and pushes data into an array.

I won't have to sort the array afterwards because it was loaded in order via mysql.

Later in the app, I will "load more" by skipping the first 100, 200 or whatever page*100 is and limit by 100 again with the same query.

The end result from the database would pref look like "this":

RESULT - selected fields from a table - field to sort on is greatest RESULT - selected fields from a possibly different table - field to sort on is next greatest RESULT - selected fields from a possibly different table table - field to sort on is third greatest etc, etc

I see a lot of simpler combined statements, but nothing quite like this.

Any help would be GREATLY appreciated.


回答1:


easiest way might be a UNION here ( http://dev.mysql.com/doc/refman/5.0/en/union.html ):

(SELECT a,b,c FROM t1)
UNION
(SELECT d AS a, e AS b, f AS c FROM t2)
ORDER BY a DESC


来源:https://stackoverflow.com/questions/6223655/best-way-to-combine-multiple-advanced-mysql-select-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!