我对一段关系的正确设计有一个问题。我的数据库只有一个名为products的表,它有以下列:
id, name, categories, price, description, extra data我需要显示分类的信息,但问题是:
我将类别保存为一个字符串,全部放在一起。
我知道我需要创建关系表,但我不知道如何调用信息。
例如,如果我创建
table: relcat
iditem (from table products)
idcategory (from table category)然后,如何将列categories中的值从表products移动到表categories?
发布于 2018-08-10 11:07:12
好的,您已经发现在单个字段中有多个数据值是个坏主意。好的。让我们继续吧。
您需要第二个表来保存与特定产品相关的存储库。考虑到在许多产品之间共享类别,您可能也需要一个类别的“主”表。
select * from categories ;
+----+------+
| id | name |
+----+------+
| 1 | Cat1 |
| 2 | Cat1 |
+----+------+
select * from products ;
+----+--------+-------+-------------+
| id | name | price | description |
+----+--------+-------+-------------+
| 11 | Fred | 1.99 | Flintstone |
| 22 | Barney | 2.99 | Rubble |
+----+--------+-------+-------------+
select * from prod_cats ;
+---------+--------+
| prod_id | cat_id |
+---------+--------+
| 11 | 1 |
| 22 | 1 |
| 22 | 2 |
+---------+--------+若要查找具有给定类别的产品:
select p.name
from products p
inner join prod_cats pc
on p.id = pc.prod_id
inner join categories c
on pc.cat_id = c.id
where c.name = 'Cat1'
order by 1 ;
+--------+
| name |
+--------+
| Barney |
| Fred |
+--------+查找所有给定类别的产品:
select p.name
from products p
where p.id in
(
select pc.prod_id
from prod_cats pc
inner join categories c
on pc.cat_id = c.id
where c.name in ( 'Cat1', 'Cat2' ) /* Categories to match */
group by pc.prod_id
having count( pc.cat_id ) = 2 /* Number of matches required */
) t0
order by 1 ;
+--------+
| name |
+--------+
| Barney |
+--------+https://dba.stackexchange.com/questions/214559
复制相似问题