[英]Mysql - Get all specific rows from one table matching criteria and relations if any from other table
I have a table of 'product type attributes' which lists the names of all possible product attributes. 我有一张“产品类型属性”表,其中列出了所有可能的产品属性的名称。
In another table I have the values for the particular attributes for a given product. 在另一个表中,我具有给定产品的特定属性的值。
I need to query the database to get all attributes names for a specific product type and their values if they have any but also if they don't have a value assigned. 我需要查询数据库以获取特定产品类型的所有属性名称以及它们的值(如果有的话)以及没有分配值的值。
For example 例如
Product type 1 : T-shirt 产品类型1:T恤
Product type 2 : Poster 产品类型2:海报
ATTRIBUTES
ID | PRODUCT_TYPE_ID | ATTRIBUTE NAME
1 | 1 | Size
2 | 1 | Colour
3 | 1 | Style
4 | 2 | Print Type
5 | 2 | Paper Type
6 | 2 | Paper Size
In the table 'product_attributes' that holds the values for these attributes (that also links it to a particular product) I have : 在表'product_attributes'中,这些表包含这些属性的值(还将其链接到特定产品),我有:
Product 1 : Men's T-shirt 商品1:男士T恤
Product 2 : Large Poster 商品2:大海报
PRODUCT_ATTRIBUTES
ID | PRODUCT_ID | ATTRIBUTE_ID | VALUE
1 | 1 | 1 | Large
2 | 1 | 2 | Blue
3 | 1 | 3 | Mens
4 | 2 | 4 | Screen print
The result I want : 我想要的结果:
Return all the attributes for a product type, even though 'print type' is the only attribute with an assigned value for that particular product. 返回产品类型的所有属性,即使“打印类型”是唯一具有该特定产品指定值的属性。
ID | PRODUCT_ID | ATTRIBUTE_ID | ATTRIBUTE_NAME | VALUE
1 | 2 | 4 | Print type | Screen print
2 | 2 | 5 | Paper type |
3 | 2 | 6 | Paper size |
I tried various JOINs but so far haven't got exactly what I want. 我尝试了各种JOIN,但到目前为止还没有我想要的。 The following returns values for other products not the specific one I need.
以下返回其他产品的值,而不是我需要的特定产品。
"SELECT
pa.value AS value,
pa.product_id AS product_id,
ptal.id AS attribute_id,
ptal.name AS attribute_name
FROM product_type_attribute_labels ptal
LEFT OUTER JOIN product_attributes pa ON ptal.id = pa.product_type_attribute_id
WHERE ptal.product_type_id = :ptid
GROUP BY ptal.id"
From what I have to this moment the following query can already provide some help 从现在起,以下查询已经可以提供一些帮助
select a.id,pa.id,ATTRIBUTE_ID,`ATTRIBUTE NAME`,value from attributes a
join product_attributes pa on a.id=pa.ATTRIBUTE_ID
where product_id = 2
Change product_id accordingly 相应地更改product_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.