从mysql表中的多行创建一个数组

时间:2012-01-28 05:16:21

标签: mysql

我有一个相当大的mysql表,它具有以下结构:

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

其中fieldid是字段的ID(在这种情况下,'10是'网站名称','20'是'网站网址','30'是'网站描述','40'是'类别')。 此外,recordid是给定网站中所有字段的ID(在这种情况下,01是Google,02是Yahoo,03是Facebook)。

我想将它们组合成一个由特定“类别”过滤的结果集(关联数组)的等价物,例如:

site            |     url            |     description
----------------|------------------------------------------
Google          | google.com         | Big search engine
Yahoo           | yahoo.com          | Other search engine

在这种情况下,它们会被“搜索引擎”过滤掉。

我试过

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

现在,虽然这很有效,但它非常非常慢,因为我需要处理的场地数量要多得多。有谁知道更好的方法来达到同样的结果?

提前致谢。

1 个答案:

答案 0 :(得分:0)

我会使用级联自联接。类似的东西:

SELECT t.content AS 'Site', t2.content AS 'URL', t3.content AS 'Description', t4.content AS 'Category'
FROM my_table AS t
LEFT JOIN my_table AS t2 ON (t2.recordid = t.recordid AND t2.fieldid = 20)
LEFT JOIN my_table AS t3 ON (t3.recordid = t.recordid AND t3.fieldid = 30)
LEFT JOIN my_table AS t4 ON (t4.recordid = t.recordid AND t4.fieldid = 40 AND t4.content = 'Search engine')
WHERE t.fieldid = 10

由于WHERE条件将显着减少结果集,假设您在(fieldid)(fieldid, recordid)上有适当的索引,则查询应该执行得更快。