Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- CREATE TABLE categories(
- id int auto_increment primary key,
- title varchar(32)
- );
- CREATE TABLE products (
- id int auto_increment primary key,
- name varchar(32),
- cat_id varchar(32)
- );
- INSERT INTO categories (title)
- VALUES
- ('Makanan'),
- ('Minuman'),
- ('Hangat'),
- ('Dingin');
- INSERT INTO products (name, cat_id)
- VALUES
- ('Bakso', '1,3'),
- ('Es Juice', '2,4'),
- ('Pudding', '1,4'),
- ('Kopi', '2,3');
- SELECT * FROM categories;
- +----+---------+
- | id | title |
- +----+---------+
- | 1 | Makanan |
- | 2 | Minuman |
- | 3 | Hangat |
- | 4 | Dingin |
- +----+---------+
- 4 rows in set (0.00 sec)
- SELECT * FROM products;
- +----+----------+--------+
- | id | name | cat_id |
- +----+----------+--------+
- | 1 | Bakso | 1,3 |
- | 2 | Es Juice | 2,4 |
- | 3 | Pudding | 1,4 |
- | 4 | Kopi | 2,3 |
- +----+----------+--------+
- 4 rows in set (0.00 sec)
- SELECT p.id, p.name, GROUP_CONCAT(c.title ORDER BY c.id) as 'categories'
- FROM products as p
- LEFT JOIN categories AS c
- ON p.cat_id REGEXP CONCAT('[,]{0,1}', c.id, '[,]{0,1}')
- GROUP BY p.id;
- +----+----------+----------------+
- | id | name | categories |
- +----+----------+----------------+
- | 1 | Bakso | Makanan,Hangat |
- | 2 | Es Juice | Minuman,Dingin |
- | 3 | Pudding | Makanan,Dingin |
- | 4 | Kopi | Minuman,Hangat |
- +----+----------+----------------+
- 4 rows in set (0.00 sec)
Add Comment
Please, Sign In to add comment