mysql - 如何检索组的所有属性并获取与组关联的给定产品的属性值

Posted

技术标签:

【中文标题】mysql - 如何检索组的所有属性并获取与组关联的给定产品的属性值【英文标题】:mysql - How to retrieve all the attributes of the group and to take attribute values for a given product that is associated with the group 【发布时间】:2014-02-16 18:30:18 【问题描述】:

如何检索组的所有属性,例如。 WHERE idGroup = '2' AND idLanguage = '1' 然后为某些 product WHERE 获取 attrValue if exists。组='2'; 如果不存在打印 attrValue = ''


例如

我的桌子

表格:产品

idProduct idGroup

表格:products_attributes

idProduct idAttr idLanguage 属性值

表格:属性

idAttr nameAttr idLanguage

表:groups_attributes

idGroup idAttr

用这个查询

SELECT a.idAttr, a.nameAttr
FROM attributes  AS a
INNER JOIN groups_attributes AS ga ON a.idAttr= ga.idAttr
WHERE ga.idGroup = 1 AND ga.idLanguage = eng

结果是

Array
(
    [0] => Array (
            [idAttr] => 1
            [idGroup] => 1
            [nameAttr] => color
        )
    [1] => Array (
            [idAttr] => 2
            [idGroup] => 1
            [nameAttr] => height
        )
    [2] => Array (
            [idAttr] => 3
            [idGroup] => 1
            [nameAttr] => width
        )
)       

如何加入表products_attributes得到这样的结果??

Array
(
    [0] => Array (
            [idAttr] => 1
            [idGroup] => 1
            [nameAttr] => color
            [idProduct] => 1
            [valueAttr] => NULL or ''
        )
    [1] => Array (
            [idAttr] => 2
            [idGroup] => 1
            [nameAttr] => height
            [idProduct] => 1
            [valueAttr] => 1600
        )
    [2] => Array (
            [idAttr] => 3
            [idGroup] => 1
            [nameAttr] => width
            [idProduct] => 1
            [valueAttr] => 900
        )
)       

我仅在设置属性值时才保存产品的属性(在此例如,未为产品 idProduct=1 设置属性 color

在编辑产品数据时,如何检索组的所有属性并获取与组关联的给定产品的属性值?

【问题讨论】:

【参考方案1】:

尝试使用左外连接和 case 语句,如下所示(您必须确保表之间的连接条件正确)。我没有在连接中包含产品表,但是如果你也想加入产品,你也离开了外部加入它。

SELECT a.idAttr, a.nameAttr, case when pa.idProduct is not null then pa.attrValue else "" end
FROM attributes  AS a
INNER JOIN groups_attributes AS ga ON a.idAttr= ga.idAttr
LEFT OUTER JOIN products_attributes AS pa ON a.idAttr=pa.idAttr
WHERE ga.idGroup = 1 AND ga.idLanguage = eng

【讨论】:

【参考方案2】:

这是加入产品的查询,如果您想要 '' 而不是 null,请使用 coalesce(pa.attrValue, '') as attrValue 代替 pa.attrValue

SELECT a.idAttr, ga.idGroup, a.nameAttr, p.idProduct, pa.attrValue
FROM attributes  AS a
INNER JOIN groups_attributes AS ga ON a.idAttr= ga.idAttr
INNER JOIN products AS p ON ga.idGroup = p.idGroup
LEFT JOIN products_attributes pa ON p.idProduct = pa.idProduct AND pa.idAttr = a.idAttr and pa.idLanguage = ga.idLanguage 
WHERE ga.idGroup = 1 AND ga.idLanguage = eng

【讨论】:

以上是关于mysql - 如何检索组的所有属性并获取与组关联的给定产品的属性值的主要内容,如果未能解决你的问题,请参考以下文章

如何通过 django 模型查询创建与组的左连接

Linux 用户与组的基本操作及文件权限位的设置方法

Linux系统用户与组的基本命令

Linux CentOS 8(用户与组相关权限管理实验)

Linux CentOS 8(用户与组相关权限管理实验)

Linux CentOS 8(用户与组相关权限管理实验)