MYSQL类数组SELECT语句

时间:2018-07-14 09:32:57

标签: php mysql arrays select


希望一切都很好。

我真的需要数据库查询/选择语句的帮助,以便在结果集/查询上使用mysqli_fetch_all后为我的PHP数组提供正确的“设计”。

我有这两个表...


产品表:

ID               Manufacturer               Product_Name
-------------------------------------------------------------------------
1                 Nike                      Air Max Talldress  
2                 Adidas                    High Voltage 


库存表:

ID            Product_ID            Color            Size            Quantity

1              1                    Black            Medium          61
2              1                    Black            Large           26
3              1                    Purple           Small           37
4              1                    Red              XSmall          88
5              2                    Green            Medium          74




这是我希望数组在发送查询并使用mysqli_fetch_all之后的样子(我不知道使用MYSQL是否可行,也许在另一个数据库管理系统中?):

Array
(
    [0] => Array
        (
            [Product_ID] => 1
            [Manufacturer] => Nike
            [Product_Name] => Air Max Talldress
            [Options] => Array
                (
                    [Black] => Medium, Large
                    [Purple] => Small
                    [Red] => XSmall
                )

        )

    [1] => Array
        (
            [Product_ID] => 2
            [Manufacturer] => Adidas
            [Product_Name] => High Voltage
            [Options] => Array
                (
                    [Green] => Medium
                )

        )

)



如果可能,以下内容也可以工作:

一个SELECT语句,为我提供特定Product_ID的所有颜色以及这些颜色的可用大小。我还需要在相同行/记录中这样做(以某种方式可以确定哪些尺寸属于正确的颜色)

当然,如果我不希望所有内容都在同一行中会更容易,但是有人可能对如何在单个行/记录中进行结构化有一个聪明的解决方案或创意。


//

2 个答案:

答案 0 :(得分:0)

已更新

select p.id, p.Manufacturer, p.Product_name, group_concat(`Color` separator ';') as `Color`
from
(
  select pid, concat(`Color`, '-',
  group_concat(`Size` separator ',')) as `Color`
  from stock
  group by pid, `Color`
) s, Products p
where p.Id = s.PId
group by p.id;

答案 1 :(得分:0)

我在这个论坛之外收到了关于我的问题的建议。我应该看看像Redis(键/值)这样的数据库。考虑到我想要的东西,也许它比MYSQL更适合我。

有什么想法吗?

相关问题