-2

我有 4 张桌子。

1.Category Table.
  Fields : Id , Name ,  Description
  Data   : 1    School  This is school


2.CategoryMeta Table
  Field : Id , CategoryId , FieldName
  Data  : 1        1        Phone
          2        1        Address

3.Object Table
  Field : Id , CategoryId , ojectName ,   ObjectDesc
           1        1        ABC School   This is a good school

4.ObjectMeta Table
  Fields : Id , CategoryId , ObjectId , CategoryMetaId , FieldValue
  Data   : 1        1           1             1          919475864253
           2        1           1             2          ABC Road.India

我想要查询的以下输出。我将类别 ID 设置为参数

ObjectId  ObjectName  ObjectDesc                Phone        Address
  1        ABC School  This is a good school   919475864253  ABC Road.India

我需要一个对象列表。任何人都可以帮助我..提前谢谢..

4

2 回答 2

1

您应该能够加入表并使用带有 CASE 表达式的聚合函数将值的行转换为列:

select o.id,
  o.ojectname,
  o.objectdesc,
  max(case when cm.fieldname = 'Phone' then om.fieldvalue end) Phone,
  max(case when cm.fieldname = 'Address' then om.fieldvalue end) Address
from object o
left join objectmeta om
  on o.id = om.objectid
left join categorymeta cm
  on om.categorymetaid = cm.id
group by o.id, o.ojectname, o.objectdesc;

请参阅SQL Fiddle with Demo。根据您使用的 RDBMS,您可以创建一个动态 SQL 版本,该版本将fieldnames根据存储在数据库中的内容获取列表。

于 2013-07-05T21:44:16.683 回答
0

这是查询,但您的架构需要一些改进。

select ph.*, om2.FieldValue as Address from
(
    select o.id as ObjectId, o.ObjectName, o.ObjectDesc,om1.FieldValue as Phone
    from object o
    join ObjectMeta om1 on o.id = om1.ObjectID
    where om1.CategoryMetaID = 1
) ph
join ObjectMeta om2 on ph.ObjectId = om2.ObjectID
where om2.CategoryMetaID = 2
于 2013-07-05T20:27:02.517 回答