Here are my DB tables:
Field
- ID, name
Order
- Order ID, name, etc.
OrderField
- Order ID
- Field ID
- Value
For example, a Field name may be “First Name,” and the OrderField value may be “James.”
Using a MySQL query only, how can I efficiently sort Orders based on the OrderFields? To be a little more specific:
Say I want a list of orders sorted by the “First Name” field, and I already have its field ID. How can I write the query to include an ORDER BY statement to sort by the “First Name” OrderField associated with the order?
Your query should be something like:
:firstNameFieldId is the id of the “First Name” field.
Outer join is used in case you have orders that do not have “First Name” field populated – they’ll still be retrieved in this case. If you’re sure this will never happen (or you don’t want them selected) replace it with an inner join.