EDIT
I’m understand the table is a mess. I took over this project and am rewriting the PHP and making serious changes to the database. I am not asking how I should layout the database. I need to make a quick, temporary fix and am looking for a better way to write the query below.
END EDIT
Hi there!
So I have this query(below) this is not finished and is getting long. I was wondering if there was a way to shorten it at all, or if there was a better way to go about it..?
SELECT user.*,
cat1id.CategoryName as cat1,
cat2id.CategoryName as cat2,
cat3id.CategoryName as cat3,
cat4id.CategoryName as cat4,
cat5id.CategoryName as cat5,
cat6id.CategoryName as cat6,
cat7id.CategoryName as cat7,
cat8id.CategoryName as cat8,
cat9id.CategoryName as cat9,
cat10id.CategoryName as cat10
FROM users AS user
LEFT JOIN Category cat1id ON user.categoryid = cat1id.id
LEFT JOIN Category cat2id ON user.categoryid_2 = cat2id.id
LEFT JOIN Category cat3id ON user.categoryid_3 = cat3id.id
LEFT JOIN Category cat4id ON user.categoryid_4 = cat4id.id
LEFT JOIN Category cat5id ON user.categoryid_5 = cat5id.id
LEFT JOIN Category cat6id ON user.categoryid_6 = cat6id.id
LEFT JOIN Category cat7id ON user.categoryid_7 = cat7id.id
LEFT JOIN Category cat8id ON user.categoryid_8 = cat8id.id
LEFT JOIN Category cat9id ON user.categoryid_9 = cat9id.id
LEFT JOIN Category cat10id ON user.categoryid_10 = cat10id.id
WHERE user.id = 65447
Thanks!
If you can’t change the database, then you’re on the right lines. If you’re going to have to work with this, then maybe a table or view that converts your mess into something more normalized would be a good idea.
EDIT: if you want to convert this into a view that is (almost) normalized, you could do something like:
etc. This code is untested, but I’m sure you get the idea. You’d have to test the performance and see if it is acceptable, but there aren’t any outer joins in there.