Need some help from a MySQL expert here. I have a terrible database to work with and I’m trying to fix the structure a bit but this one has me baffled. The table initially had an id, name and 4 sell columns. I converted that to an id, name and single sell column as basically a pivot table. That was fine, next issue was to get rid of duplicates since not every entry had 4 sell entries.
So after the first operation I ended up with something like this:
id name sellid
1 bob 111
1 bob
1 bob
2 mary 112
2 mary 113
2 mary 114
2 mary 115
3 fred
3 fred
3 fred
3 fred
So by doing group by I managed to get it to the point where it looks like this:
id name sellid
1 bob 111
1 bob
2 mary 112
2 mary 113
2 mary 114
2 mary 115
3 fred
Now here is where I hit a wall. Fred is fine, he is supposed to have an entry but no sellid, Mary is also fine she has all 4 sellids full. Bob is the issue. How do I remove the empty sellid for him without affecting Fred?
I’d say what I tried but I am just at a complete loss here so I really haven’t tried anything yet.
You are looking for an outer join between your names and other data:
See it on sqlfiddle.
But really, you should normalise your schema further so that you have a table of
(personid, name)and a table of(personid, sellid)pairs (from which you essentially perform the above outer join as & when required to obtain the necessary records includingNULLs).