Another approach is to create a view with your $complex_where_logic$ and query the view instead of the tables:
CREATE VIEW my_view AS SELECT * FROM sometable WHERE $complex_where_logic$
SELECT my_column FROM my_view ORDER BY some_column
Whenever you query a view, you always get the up-to-date data. Internally, MySQL runs the SELECT
given in the CREATE VIEW
statement and queries the results in order to obtain the results of your current SELECT
. Therefore, a view does not improve performance compared to a single query. There a two main advantages in using views:
- you have simpler SELECT statements since you do not have to type complex WHERE or JOIN Syntax again and again
- you can use it to control user privileges, e.g. give a user access to a view but not to the original tables; this is not useful in your example, but - for example - you can think of views containing aggregate data only