gpt4 book ai didi

MySQL 通过特殊 ID 搜索

转载 作者:太空宇宙 更新时间:2023-11-03 12:33:08 25 4
gpt4 key购买 nike

我有项目和这个项目的类别。类别有一个ID。我需要将项目的类别 ID 放入数据库中,但项目可以有 2,3 个或更多类别。我需要做什么?

在项目表中创建一个新的单元格名称“category”并将类别 id 与逗号 (7,4,8...) 放在一起?如果这样,那么如何在 PHP 中按类别搜索?

最佳答案

如果我理解你的问题,你有一个可以有多个类别的项目。如果是这种情况,则不要将多个类别存储在同一列中。

您可能希望以这种方式设置表格:

create table item
(
id int, (PK)
name varchar(10)
);

create table category
(
id int, (PK)
name varchar(10)
);

create table item_category
(
item_id int, (FK)
category_id int (FK)
);

这将允许您将项目和类别放在单独的表中,然后使用连接表允许您的项目具有多个类别。

如果您有上述表格的以下样本数据:

insert into item values
(1, 'item 1'),
(2, 'item 2');

insert into category values
(1, 'category 1'),
(2, 'category 2');

insert into item_category values
(1, 1),
(2, 1),
(2, 2);

那么您的查询将与此类似:

select i.id item_id,
i.name ItemName,
c.id CategoryId,
c.name CategoryName
from item i
left join item_category ic
on i.id = ic.item_id
left join category c
on ic.category_id = c.id

参见 SQL Fiddle with Demo .结果是:

| ITEM_ID | ITEMNAME | CATEGORYID | CATEGORYNAME |
--------------------------------------------------
| 1 | item 1 | 1 | category 1 |
| 2 | item 2 | 1 | category 1 |
| 2 | item 2 | 2 | category 2 |

关于MySQL 通过特殊 ID 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14440493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com