我有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
我需要一个对象列表。任何人都可以帮助我.. 提前谢谢..
答案 0 :(得分: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
列表。
答案 1 :(得分: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