【问题标题】:MySQL query AND PHP challenge..Splitting Semicolon valuesMySQL查询和PHP挑战..分割分号值
【发布时间】:2024-10-11 07:45:02
【问题描述】:

我正在使用 PHP/代码点火器来显示数据。 在我的表(产品)中,我有一个名为“ProductCategory”的字段。由于一个产品可以属于多个类别,并且根据我的项目要求和 XML 文件,该字段的填充如下:

id 121

产品代码 m34

名称诺基亚 6800

产品类别手机;外壳

ProductMainCategory手机

排序顺序 3

///////////////////第二个产品//////////////////// ///

id 344

产品代码 32344

名称 Xbox 360 Black

ProductCategory控制台

ProductMainCategory特别优惠

排序顺序 5

///////////////////第三产品//////////////////// ///

id 3433

产品代码 342zxc4

名称 Iphone 5

产品类别配件;手机 4G

ProductMainCategory手机

排序顺序 3

等等.....

问题:

因为,我用分号 (;) 将产品分为两个类别,所以 拆分了分号产品类别';'值分为两类,并在 url 中传递它们以根据“ProductCategory”和“ProductMainCategory”显示产品。 我正在使用查询字符串 /uri 段来显示我的产品。

<?
$id2=urldecode($this->uri->segment(3)); //  gets values like Handsets
$id=urldecode($this->uri->segment(4));  // gets values like Mobiles
$this->db->like('ProductCategory',$id);

$this->db->or_like('ProductCategory',';'.$id);
//$this->db->not_like('ProductCategory','Store 8');
//$this->db->like('ProductCategory',';'.$id);
$this->db->where('ProductMainCategory',$id2);
$this->db->order_by('sort_order','asc');
$query_data=$this->db->get('Products');
?>

基于代码和MYSQL数据,我如何显示我的单个产品,以便它可以单独出现在每个类别下(根据查询字符串/uri段值),如下所示:

Handsets¬
         |-Mobiles
                  |--- Nokia 6800
         |-Casings
                  |---- Nokia 6800    

         |-Mobiles 4G
                  |--- Iphone 5 
         |-Accessories
                  |---- Iphone 5    


  Special Offers¬
                |-Consoles
                         |---Xbox 360 Black  

我已经在树结构中显示了所需的查询输出以进行澄清。您可以将其与上面的数据进行比较以进行澄清。请帮助我。谢谢

【问题讨论】:

  • 我知道规范化。我想要单个表中的重复值,因为这是项目的要求
  • 数据库设计不好是项目的要求吗?
  • @MarkBaker。在过去 6 年的开发中,我一直在使用规范化技术。在这种情况下,我直接从 SAGE XML 转储数据,而 XML 不知道规范化。是吗? ? :)
  • @Bilal Khalid 来吧,只需摆脱 ProductCategory 并使用 product_to_category 关系实现它。然后,您可以通过简单的 JOIN 实现所需的目标。

标签: php mysql codeigniter


【解决方案1】:

假设您有一个名为 ProductCategories 的有效产品类别表。您可以使用复杂的连接条件按类别获取产品。这是一个计算每个类别中产品数量的示例:

select pc.ProductCategory, count(*) as NumProducts
from Products p join
     ProductCategories pc
     on concat(';', p.ProductCategory, ';') like concat('%;', pc.ProductCategory, '%;')
group by pc.ProductCategory

如果您没有 ProductCategories 表,您可以在查询中创建一个:

select pc.ProductCategory, count(*) as NumProducts
from Products p join
     (select 'Console' as ProductCategory union all
      select . . .
     ) pc
     on concat(';', p.ProductCategory, ';') like concat('%;', pc.ProductCategory, '%;')
group by pc.ProductCategory

但是,我只建议对临时一次性查询执行此操作,因为随着时间的推移可能会添加新类别。

【讨论】: