0

我有一个 SQL Server 数据库,我需要存储未知数量的列,所以我有 2 个这样的表:

  1. Master,包含这些列:(id, data1, data2固定列)
  2. unknown_fields包含这些列的表:id_master_record, id_field, value_field

我做这样的查询:

SELECT id, data1, data2, 
  (SELECT value_field FROM unknown_fields
    WHERE id_master_record = Master.id AND id_field = 1) AS data3
  (SELECT value_field FROM unknown_fields 
    WHERE id_master_record = Master.id AND id_field = 2) AS data4
  (SELECT value_field FROM unknown_fields 
    WHERE id_master_record = Master.id AND id_field = 3) AS data5
 ... SO for each 
FROM Master

我想知道是否有更好的方法来做这个查询。

4

3 回答 3

4

你可以试试这个,它可能会稍微快一点。最好两个都测试。对第二个表进行聚类(id_master_record, id_field)可能会对这两个查询都有帮助。

Select
  m.id,
  m.data1,
  m.data2,
  Max(Case u.id_field When 1 Then u.value_field End) As data3,
  Max(Case u.id_field When 2 Then u.value_field End) As data4,
  Max(Case u.id_field When 3 Then u.value_field End) As data5
From
  xmaster m
    Left Outer Join
  unknown_fields u
    On m.id = u.id_master_record
Group By
  m.id,
  m.data1,
  m.data2;

您也可以尝试使用Pivot

Select
  id,
  data1,
  data2,
  [1] as data3,
  [2] as data4,
  [3] as data5
From (
  Select
    m.id,
    m.data1,
    m.data2,
    id_field,
    value_field
  From
    Master m
      left outer join
    unknown_fields u
      On m.id = u.id_master_record
    ) as s
Pivot (
  max(value_field)
For 
    id_field In ([1], [2], [3])
) As p;

http://sqlfiddle.com/#!6/f9bca/11

于 2012-12-03T23:47:48.120 回答
1

您的初始查询是完成您需要的相当好的方法,相反我可能会建议您查看查询执行计划,并尝试提高 field_id 上的索引,也许这会加快您的查询速度。

于 2012-12-04T10:47:38.120 回答
0

另一种可能的重写:

SELECT Master.id, Master.data1, Master.data2, 
       u3.value_field AS data3,
       u4.value_field AS data4,
       u5.value_field AS data5,
       ... so for each 
FROM Master
  LEFT JOIN unknown_fields AS u3
    ON  u3.id_master_record = Master.id 
    AND u3.id_field = 1
  LEFT JOIN unknown_fields AS u4
    ON  u4.id_master_record = Master.id 
    AND u4.id_field = 2
  LEFT JOIN unknown_fields AS u5
    ON  u5.id_master_record = Master.id 
    AND u5.id_field = 3
  ... so for each  ;

如果您想优化性能,您应该检查各种重写的执行计划,并在您的服务器中使用您的数据进行测试。表上的索引对于效率至关重要。聚集索引的选择,尤其是表的选择unknown_fields也会影响这个查询。

unknown_fieldsare(id_master_record, id_field, value_field)和 the(不同排序)的两个可能索引:(id_field, id_master_record, value_field)

于 2012-12-04T00:11:27.783 回答