[英]How to display all rows from one table if there are no rows with matching criteria to count in second table
[英]Mysql - Get all specific rows from one table matching criteria and relations if any from other table
我有一張“產品類型屬性”表,其中列出了所有可能的產品屬性的名稱。
在另一個表中,我具有給定產品的特定屬性的值。
我需要查詢數據庫以獲取特定產品類型的所有屬性名稱以及它們的值(如果有的話)以及沒有分配值的值。
例如
產品類型1:T恤
產品類型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
在表'product_attributes'中,這些表包含這些屬性的值(還將其鏈接到特定產品),我有:
商品1:男士T恤
商品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
我想要的結果:
返回產品類型的所有屬性,即使“打印類型”是唯一具有該特定產品指定值的屬性。
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 |
我嘗試了各種JOIN,但到目前為止還沒有我想要的。 以下返回其他產品的值,而不是我需要的特定產品。
"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"
從現在起,以下查詢已經可以提供一些幫助
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
相應地更改product_id
檢查這個sqlfiddle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.