Skip to content
Advertisement

How does a prioritization query work (one value is preferred over another if a criteria is met)

DB-Fiddle

The table displays different campaigns and their status within the purchasing process using event_types.
The process is as the following:


Based on this structure the result should look like this:

In order to achieve this I go with the prioritization query described in the question here:

This query gives me exactly the result I need.
However, I am wondering how this query actually works because when I run only this part:

The result is just:

How does the query know which of the event_type comes after stored?

Advertisement

Answer

DB Fiddle

Step 1:
The correlated subquery – in this case WHERE p2.campaign = p.campaign – goes through all campaigns and identifies all available event_types per campaign.
Basically, the inner query is re-executed for each campaign

https://en.wikipedia.org/wiki/Correlated_subquery


Step 2:
Afterwards all available results per campaign are ordered by the defined hierarchy of the event_type in the field function.

https://www.w3resource.com/mysql/string-functions/mysql-field-function.php


Step 3:
Finally, the LIMIT 1 only leaves the highest available event_type in the result and thus the WHERE clause of the outer query gets the highest event_type per campaign.

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