I have a rather large mysql table that has the following structure:
fieldid | recordid | content
----------------------------
10 | 01 | Google
10 | 02 | Yahoo
10 | 03 | Facebook
20 | 01 | google.com
20 | 02 | yahoo.com
20 | 03 | facebook.com
30 | 01 | Big search engine
30 | 02 | Other search engine
30 | 03 | Largest Social Network
40 | 01 | Search engine
40 | 02 | Search engine
40 | 03 | Social Network
Where fieldid is the id for the field (in this case ’10 is the ‘site name’, ’20’ is the ‘site url’, ’30’ is the ‘site description’ and ’40’ is the ‘category’).
Also, recordid is the id for all the fields in a given website (in this case 01 is Google, 02 is Yahoo and 03 is Facebook).
I would like to combine them into the equivalent of a result set (associative array) filtered by a particular ‘category’ such as:
site | url | description
----------------|------------------------------------------
Google | google.com | Big search engine
Yahoo | yahoo.com | Other search engine
Where in this case they are filtered by “Search engine”.
I tried
SELECT
recordid,
GROUP_CONCAT( if( fieldID = 10, content, NULL ) ) AS 'site',
GROUP_CONCAT( if( fieldID = 20, content, NULL ) ) AS 'url',
GROUP_CONCAT( if( fieldID = 30, content, NULL ) ) AS 'description',
GROUP_CONCAT( if( fieldID = 40 and content = 'Search engine', content, NULL ) ) AS 'category'
FROM my_table
GROUP BY recordid
HAVING Category IS NOT NULL
Now, although this works, it is very, very slow because there are far more fieldids than the ones I need to process. Does anyone know of a better way to achieve the same result?
Thanks in advance.
I’d use cascading self joins. Something like:
Since the
WHEREcondition is going to significantly reduce the resultset, the query should perform faster, assuming you have appropriate indexes on(fieldid)and(fieldid, recordid).