2016-05-28 4 views
0

Ich habe eine Frage zu einer Abfrage. Es gibt zwei Tabellen:Abfrage Attribute, wo ein Attribut fehlt

Objects table: 
============== 
Object ID Date 
1  2016-03-15 
2  2016-01-20 

Attributes table: 
================= 
Parent ID Attribute AttributeData 
1  Size  XL 
2  Size  S 
2  Price  20 

The query is to join the data to get this: 
========================================== 
Objet ID Size Price 
1  XL NULL 
2  S 20 

But I only get this: 
========================================== 
Objet ID Size Price 
2  S 20 

A LEFT JOIN hilft nicht - weil es für Preis für ID1 kein Eintrag in der Attributtabelle ist.

Es tut mir leid, dass so ein Neuling auf diesem.

Froh für jede Hilfe.

Steffen

+0

Bitte posten Sie Ihre bestehende Anfrage. Bitte klären Sie auch, welche Datenbank Sie verwenden, da dies die Antwort beeinflusst. – Alex

Antwort

2

Ich denke bedingte Aggregation tut, was Sie wollen:

select parentid, 
     max(case when attribute = 'Size' then attributedata end) as size, 
     max(case when attribute = 'Price' then attributedata end) as price 
from attributes 
group by parentid; 

ein left join Verwendung Sie tun würde:

select o.*, s.attributedata as size, p.attributedata as price 
from objects o left join 
    attributes s 
    on o.objectid = s.parentid and s.attribute = 'Size' left join 
    attributes p 
    on o.objectid = p.parentid and p.attribute = 'Price'; 

Beachten Sie, dass für diese die Bedingung für die Arbeit, Attributname muss in der on Klausel sein, nicht eine where Klausel.

Verwandte Themen