2013-02-10 13 views
0

我有一種情況,我必須使用EAV表設計。如何從EAV表格設計中查詢多行?

我有以下兩張表。

節點

id name structure_id 
1 name 1  7 
2 name 2  7 

屬性

id node_id name  value structure_id 
1  1  firstname test   7 
2  1  lastname test   7 
3  2  firstname test   7 

我有以下查詢

SELECT n.*, GROUP_CONCAT(CONCAT_WS('||', a.name, a.value) ORDER BY a.name SEPARATOR ';;') as _attributes 
      FROM nodes n JOIN attributes a ON n.structure_id = a.structure_id where n.structure_id = 7 

上面的查詢輸出下面的(只有一行)

id: 1 
name: name 1 
structure_id: 7 
_attributes: firstname||test;;firstname||test;;firstname||test;;firstname||test;;lastname||test;;lastname||test 

如何使其輸出節點表的兩行用自己的行從屬性

+0

變化'ORDER BY a.name'到'GROUP BY a.name'。或者,您也可以添加「GROUP BY node_id」子句。 – hjpotter92 2013-02-10 07:44:43

+0

@BackinaFlash //嗨,我已經嘗試了他們兩個。沒有工作.. – Moon 2013-02-10 07:47:29

+1

http://sqlfiddle.com/#!2/0ebd1/18似乎正在產生一點點好結果。它仍然具有來自屬性表的所有值。 – hjpotter92 2013-02-10 08:02:57

回答

2

如果通過structure_id和node_id連接節點和屬性表,您將獲得所需的結果集。 期望的結果集:「來自節點表,其中來自屬性的行」。

好運

1
select n.id,n.name,n.structure_id,firstname,lastname from Nodes n 
join (select node_id, a.value as firstname from Attributes a where a.name='firstname') matches1 on matches1.node_id = n.id 
left join (select node_id, a.value as lastname from Attributes a where a.name='lastname') matches2 on matches2.node_id = n.id 
+0

謝謝..但它需要是動態的。我不能硬編碼'名字' – Moon 2013-02-12 06:57:40