简体   繁体   English

具有属性和内部联接的MySQL查询

[英]MySQL Query with properties and inner joins

I have 3 tables and testdata, see below. 我有3个表和testdata,请参见下文。

How can i get this output doing a query? 我如何获得此输出进行查询?

Itemname     Name        Address
========================================
Test Item 1  test name 1 test address 1
Test Item 2  test name 2 test address 2

Table Item : Item

id   Name
========================================
1 - Test Item 1
2 - Test Item 2

Table Itemproperties : 表项目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

Table Properties : Properties

id name
===========
1  name
2  address

You will need to join the Itemproperties table twice, once for the name and once for the address: 您将需要两次连接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

One way to do it is to hard code on name and address. 一种方法是对名称和地址进行硬编码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM