我有3个表和testdata,见下文。
如何让这个输出进行查询?
Itemname Name Address
========================================
Test Item 1 test name 1 test address 1
Test Item 2 test name 2 test address 2
表Item
:
id Name
========================================
1 - Test Item 1
2 - Test Item 2
表Itemproperties
:
id item_id property_id value
======================================
1 1 1 test name 1
1 1 2 test address 1
1 2 1 test name 2
1 2 2 test address 2
表Properties
:
id name
===========
1 name
2 address
答案 0 :(得分:2)
您需要两次加入Itemproperties表,一次是名称,一次是地址:
SELECT
i.name Itemname,
ip1.value Name,
ip2.value Address
FROM
Item i
JOIN Itemproperties ip1 ON i.id = ip1.item_id AND ip1.property_id = 1
JOIN Itemproperties ip2 ON i.id = ip2.item_id AND ip2.property_id = 2
答案 1 :(得分:0)
一种方法是对名称和地址进行硬编码。
SELECT I.Itemname,IPN.value AS Name, IPA.value AS Address
FROM Item I
LEFT JOIN Itemproperties IPN
ON IPN.item_id=I.id
LEFT JOIN Itemproperties IPA
ON IPA.item_id=I.id
WHERE IPN.property_id=1 AND IPA.property_id=2