Change the order of a table according to preference in another table
It is too long for a comment.

Well, that's the problem, then. I take data from A, then apply overrides from B to it and end up with a cycle. I think that there is a cycle, you don't think that there should be a cycle.

So, there is a bigger problem with understanding how overrides should work.

My logic is the following.

Data from A can be represented in the same format as B:

Name   Food    PreferenceOrder
Jon    Burger  1
Jon    Coke    2
Jon    Pizza   3
Jon    Fries   4


So, for Jon we have this chain originally:

Burger -&gt; Coke -&gt; Pizza -&gt; Fries


OR this set of rules:

a) Burger -&gt; Coke
b) Coke -&gt; Pizza
c) Pizza -&gt; Fries


Then we have overrides from B:

Name   Food    PreferredOverFood
Jon    Pizza   Fries
Jon    Coke    Burger
Jon    Fries   Coke


OR this set of rules:

d) Pizza -&gt; Fries
e) Coke -&gt; Burger
f) Fries -&gt; Coke


Now we merge two sets of rules where second set overrides the first set if there is a conflict.

Rule (d) is the same as (c), so (c) is removed.
Rule (e) overrides (a), so (a) is removed.
Rule (f) is a new rule that doesn't exist in the first set.
If any rules from the first set are still there, they are kept.

Final result of rules:

d) Pizza -&gt; Fries
e) Coke -&gt; Burger
f) Fries -&gt; Coke
b) Coke -&gt; Pizza


This is a directional graph. If it represents a tree, it can be ordered. It there are cycles, you need to decide what to do with them. If there are several disconnected trees, you can order each tree individually and then decide the order between trees.

In your example the graph looks like this (if we start from Coke).

    (b)      (d)      (f)
Coke -&gt; Pizza -&gt; Fries -&gt; Coke -&gt; ... the cycle (bdf) ...
   |
   | (e)
   |
   -&gt; Burger