0

我这里有一个表 SQL

| id | dataid |  datarow | datacolumn | datavalue
_________________________________________________
|  1  |  1     |     1    | FirstName   |  John
|  1  |  1     |     1    | LastName    |  Lobo
|  1  |  1     |     1    | Age         |  35
|  1  |  1     |     2    | FirstName   |  Mich
|  1  |  1     |     2    | LastName    |  Handness
|  1  |  1     |     2    | Age         |  22
|  1  |  1     |     3    | FirstName   |  Mike
|  1  |  1     |     3    | LastName    |  Longbow
|  1  |  1     |     3    | Age         |  55

哪个会输出这样的东西

FirstName  LastName Age
   John      Lobo   35
   Mich      Handness 22
   Mike      Longbow  55
SELECT DISTINCT     
        t1.datavalue AS Firstname, 
        t2.datavalue AS Lastname,
        t3.datavalue AS Age

FROM largedatatable t1 
        LEFT JOIN (SELECT datavalue,datarow FROM largedatatable WHERE           datacolumn='LastName') t2 ON t1.datarow = t2.datarow
        LEFT JOIN (SELECT datavalue,datarow FROM largedatatable WHERE datacolumn='Age') t3 ON t1.datarow = t3.datarow

WHERE t1.dataid = 1 

这给了我这样的结果

Firstname  LastName   Age
John        Lobo      35
Mich      Handness    22
Mike      Longbow     55

现在脚本工作得很好;但是如果它的数据集很大,查询会很慢。无论如何我仍然可以优化这个 SQL 查询。谢谢!

4

2 回答 2

1

我认为这会解决您的问题,或者至少它会运行得更快,因为它只会获取表一次:

select 
    max(case datacolumn when 'FirstName' then datavalue else '' end) as FirstName,
    max(case datacolumn when 'LastName' then datavalue else '' end) as LastName,
    max(case datacolumn when 'Age' then datavalue else '' end) as Age
from 
    large
group by datarow

在小提琴上看到它:http ://sqlfiddle.com/#!2/f4045/11

于 2013-11-13T14:07:47.573 回答
0

我会确保您在 ( datarow, datacolumn ) 上有一个索引来帮助您加入,但您的加入可以简化为

SELECT 
        t1.datavalue AS Firstname, 
        t2.datavalue AS Lastname,
        t3.datavalue AS Age
   FROM 
      largedatatable t1
         LEFT JOIN largedatatable t2
            on t1.datarow = t2.datarow
           and t2.datacolumn = 'LastName'
         LEFT JOIN largedatatable t3
            on t1.datarow = t3.datarow
           and t3.datacolumn = 'Age'
   WHERE
      t1.datacolumn = 'FirstName'

这只会根据第一个名称列通过您的主表一次,但从第二个实例中提取列,而不需要聚合的 MAX() 或 GROUP BY。

于 2013-11-13T13:42:30.660 回答