Vi Veri Veniversum Vivus Vici
For example, we have some table for categories:

  1. CREATE TABLE `p1` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `title` varchar(20) DEFAULT NULL,
  4. PRIMARY KEY (`id`)
  5. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
We have some categories:

  1. mysql> select * from p1;
  2. +----+-------+
  3. | id | title |
  4. +----+-------+
  5. | 1 | cat1 |
  6. | 2 | cat2 |
  7. | 3 | cat3 |
  8. | 4 | cat4 |
  9. +----+-------+
  10. 4 rows in set (0.00 sec)
Then, we have table for properties:

  1. CREATE TABLE `p2` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `title` varchar(20) DEFAULT NULL,
  4. `cat_id` int(11) NOT NULL,
  5. PRIMARY KEY (`id`)
  6. ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;

There are list of properties:

  1. mysql> select * from p2;
  2. +----+--------+--------+
  3. | id | title | cat_id |
  4. +----+--------+--------+
  5. | 1 | prop11 | 1 |
  6. | 2 | prop12 | 1 |
  7. | 3 | prop21 | 2 |
  8. | 4 | prop22 | 2 |
  9. | 5 | prop23 | 2 |
  10. | 6 | prop31 | 3 |
  11. | 7 | prop32 | 3 |
  12. | 8 | prop33 | 3 |
  13. | 9 | prop41 | 4 |
  14. +----+--------+--------+
  15. 9 rows in set (0.00 sec)

Next, we need to have list of properties values, which may be contained in "groups":

  1. CREATE TABLE `p3` (
  2. `gid` int(11) NOT NULL,
  3. `prop_id` int(11) NOT NULL,
  4. `value` varchar(20) DEFAULT NULL,
  5. PRIMARY KEY (`gid`,`prop_id`)
  6. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

with the following content:

  1. mysql> select * from p3;
  2. +-----+---------+------------+
  3. | gid | prop_id | value |
  4. +-----+---------+------------+
  5. | 1 | 1 | prop 1 |
  6. | 1 | 2 | prop 2 |
  7. | 1 | 4 | diff value |
  8. | 1 | 5 | same value |
  9. | 1 | 6 | prop 6 |
  10. | 2 | 1 | prop 1 |
  11. | 2 | 2 | prop 2 |
  12. | 2 | 3 | prop 3 |
  13. | 2 | 4 | prop 4 |
  14. | 2 | 5 | same value |
  15. | 2 | 7 | prop 7 |
  16. +-----+---------+------------+
  17. 11 rows in set (0.00 sec)

For example, I want to know, which values of second group are missed or have different value in the first group. And properties in this dataset must be included in categories 1 and 2.


  1. mysql> select *,
  2. (select b.prop_id
  3. from p3 as b
  4. where gid = 1
  5. and a.prop_id = b.prop_id
  6. ) as is_exists
  7. from p3 as a
  8. join p2
  9. on p2.id = a.prop_id
  10. where gid = 2
  11. and cat_id in (1, 2)
  12. and (prop_id, value) not in
  13. (select prop_id, value
  14. from p3
  15. where gid = 1
  16. and prop_id = a.prop_id
  17. );
  18. +-----+---------+--------+----+--------+--------+-----------+
  19. | gid | prop_id | value | id | title | cat_id | is_exists |
  20. +-----+---------+--------+----+--------+--------+-----------+
  21. | 2 | 3 | prop 3 | 3 | prop21 | 2 | NULL |
  22. | 2 | 4 | prop 4 | 4 | prop22 | 2 | 4 |
  23. +-----+---------+--------+----+--------+--------+-----------+
  24. 2 rows in set (0.00 sec)


@темы: MySQL