Skip to content
Advertisement

How to sort an EAV model that have null values?

We have an EAV (Entity-Attribute-Value) data model that can be simplified with those 3 tables:

enter image description here

We want to sort entities on certain field:

However, this will not include entities that do not have values for this field. The wanted behavior would be to have those NULL entries at the beginning of the result, like usual ORDER BY.

Do you have suggestion of how to include those values ? Thanks

EDIT: Here is a concrete example:

Imagine we want to display and sort a list of 3 users, which are 3 entities having 2 fields, name and age:

The Entity table:

The Field table:

The Value table:

Here, Charlie have no value for age. How to sort users by the age field without removing Charlie ?

The above query will remove it from the result-set.

Advertisement

Answer

Note: I’m still somewhat confused about what you want your resultset to look like.

Result:


Or if you prefer the names of the fields:

Result:


For the case where there’s an entity, that doesn’t have a firstname, I added two rows to entity and a row to value:

If a record exists in the entity table, it will always be in this result:

Result:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement