php - Complex MySQL-query, union, intersect or natural join?
Having an odd problem with a MySQL query, I can't really figure out how to get the data organized as I wish.
I'm building search-script in PHP, but the database structure isn't in the way that I would like.
Okay, say that I have three tables (these are completely made up):
EMPLOYES
id name city hired
Now, if I stick to LEFT JOINs etc. I am able to get a result that look like this, where it repeats every row in in the Salary table:
{-code-2}
But what I really want is something like this:
{-code-3}
Any way that I can achieve this with SQL?
Answer
Answer
Answer
Answer
Answer
Answer
Solution:
You need a
PIVOT
query. As your tables are made up anyway I'll work off this made up table so you can see the approach.To pivot this you would use
Answer
Answer
Solution:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
But you better do it by hand, not in SQL. When I say "by hand" I mean by writing a program that does that for you. We are all programmers here, aren't we?
Answer
Solution:
As Martin commented, what youre looking for is called PIVOT in SQL Server. AFAIK MySQL doesn't support it. If you know the year range youre intrested in beforehand then you should be able to constructing the query using LEFT JOINs, something like