MySQL Forums
Forum List  »  General

Re: Need help with query (dynamic)
Posted by: Devart Team
Date: June 11, 2010 06:11AM

Try this code -

CREATE TABLE items (
  id INT(11) DEFAULT NULL,
  title VARCHAR(255) DEFAULT NULL,
  owner VARCHAR(255) DEFAULT NULL
);

CREATE TABLE properties (
  id INT(11) NOT NULL,
  item_id INT(11) DEFAULT NULL,
  `key` VARCHAR(255) DEFAULT NULL,
  val VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (id)
);

INSERT INTO items VALUES 
  (1, 'lorem', '1'),
  (2, 'ipsum', '1'),
  (3, 'dolor', '2'),
  (4, 'sit', '1'),
  (5, 'amet', '3');

INSERT INTO properties VALUES 
  (1, 1, 'color', 'blue'),
  (2, 1, 'size', 'large'),
  (3, 2, 'color', 'orange'),
  (4, 3, 'size', 'small'),
  (5, 4, 'color', 'violet'),
  (6, 5, 'color', 'green');

SELECT
  i.*,
  p.color,
  p.size
FROM
  items i
  JOIN
    (
    SELECT
      item_id,
      MAX(IF(`key` = 'color', val, NULL)) AS color,
      MAX(IF(`key` = 'size', val, NULL)) AS size
    FROM
      properties
    GROUP BY
      item_id) p
    ON i.id = p.item_id;
+------+-------+-------+--------+-------+
| id   | title | owner | color  | size  |
+------+-------+-------+--------+-------+
|    1 | lorem | 1     | blue   | large |
|    2 | ipsum | 1     | orange | NULL  |
|    3 | dolor | 2     | NULL   | small |
|    4 | sit   | 1     | violet | NULL  |
|    5 | amet  | 3     | green  | NULL  |
+------+-------+-------+--------+-------+

Devart Company,
MySQL management tools
http://www.devart.com/dbforge/mysql/

Options: ReplyQuote


Subject
Written By
Posted
Re: Need help with query (dynamic)
June 11, 2010 06:11AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.