Saturday, 15 February 2014

sql - MySQL query concatenating more than 1 related table -


My question is about getting multiple values ​​of the property in a string without replacing the main line.

To illustrate my problem, I will use a simple example:

unit - Relationship Diagram

I want to get some elements of" table "with the inclusion of an asset in one area and one Want to critique the property in other areas I am However, it is important to duplicate the lines of "table" at any time, for example, a row that meets row 1 and row 4 should look like this:

  1 line1 "P1_1 , P1_2 database structure / example of data:  
  create table table 1 (id INT AUTO_INCREMENT, P2_1, P2_2 "4 Row4" P1_3 "" P2_3 "  

Price VARCHAR (10), Primary Key (ID)) engine = INNODB DEFAULT CHARSET = latin1; Table property (ID INT AUTO_INCREMENT, value VARCHAR (10), Table 1 INT, primary key (ID), foreign key (Table 1) Reference Table 1 (ID) CASCADE update on IDE CASCADE engine = INNODB DEFAULT CHARSET = latin1; Table property creation (ID INT AUTO_INCREMENT, value VARCHAR (10), Table 1 INT, Primary key (ID), Foreign key (Table 1) Reference Table 1 (ID) CASADED UPDATE at IDE CASCADE) Engine = INNODB DEFAULT CHARSET = latin1 ; Insert in Table 1 (Value) values ​​('line1'), ('line2'), ('row3'), ('row4'), ('row 5'), ('row 6') ; INSERT ('P1_1', 1), ('P1_2', 1), ('P1_3', 4), ('P1_4', 6) in Properties (Value, Table 1); Insert into property (value, table 1) value ('P2_1', 1), ('P2_2', 1), ('P2_3', 4), ('P2_4', 5);

I have tried some questions:

  SELECT t *, GROUP_CONCAT (p1.value), GROUP_CONCAT (p2.value) Table 1T Insert from left to property1 p1.table1 = t.id on p1 Insert property 2 p2 at p2.table1 = t.id WHERE t. TID by id IN (1,4) group;   

But the result properties 1 and property_2 are duplicating the values ​​in the string.

Like this:

How to get separate lines in Table 1 Is your properties added to the string?

Quick Reply: Use the difference within your group - therefore:

  SELECT t *, Insert GROUP_CONCAT (separate p1.value), GROUP_CONCAT (separate p2.value) from table 1t left on property_1 p1 p1.table1 = t.id LEFT JOIN property_2 P2 on p2.table1 = t.id WHERE t. TID by id IN (1,4) group;   

SQLFiddle.

No comments:

Post a Comment