[英]MySQL multiple selects in one query
例如,我有幾個表:
產品介紹:
| product_id | name | price |
| 1 | apple | 20.32 |
| 2 | pear | 9.99 |
| 3 | banana | 1.5 |
產品屬性:
| attr_id | name | value |
| 1 | weight | 10 kg |
| 2 | date | 2013 |
| 3 | color | red |
...等等。
最后產品-屬性關系表:
| product_id | attr_id |
| 1 | 3 |
| 2 | 1 |
| 1 | 2 |
| 3 | 2 |
我的問題:是否存在可用的構造一選擇請求查詢,該查詢在以下數據結構(或類似數據)中返回產品1和2? 現在,我應該先運行deveral選擇請求“ where product_id IN(1、2)”,然后遍歷循環選擇它們的屬性。
對不起,英語不好:]
array(
[0] = array(
product_id = 1,
name = apple,
attributes= array(
[0] => array(
attr_id = 3,
name = color,
value = red,
),
[0] => array(
attr_id = 2,
name = date,
value = 2013,
)
),
),
[1] = array(
product_id = 2,
name = apple,
attributes= array(
[0] => array(
attr_id = 1,
name = veight,
value = 10 kg,
),
),
)
)
這不僅與查詢有關,還與PHP代碼有關。 這將適合:
$rSelect = mysqli_query('SELECT
products.id AS record_id,
products.name AS products_name,
products.price AS product_price,
attributes.id AS attribute_id,
attributes.name AS attribute_name,
attributes.value AS attribute_value
FROM
products
LEFT JOIN products_attributes
ON products.id=products_attributes.product_id
LEFT JOIN attributes
ON products_attributes.attr_id=attributes.id', $rConnect);
$rgResult = [];
while($rgRow = mysqli_fetch_array($rSelect))
{
$rgResult[$rgRow['record_id']]['product_id'] = $rgRow['record_id'];
$rgResult[$rgRow['record_id']]['name'] = $rgRow['product_name'];
$rgResult[$rgRow['record_id']]['price'] = $rgRow['product_price'];
$rgResult[$rgRow['record_id']]['attributes'][] = [
'attr_id' => $rgRow['attribute_id'],
'name' => $rgRow['attribute_name'],
'value' => $rgRow['attribute_value'],
];
};
//var_dump($rgResult);
您要查找的查詢是:
select
p.product_id,
p.name as product_name,
a.attr_id,
a.name as attr_name,
a.value
from
products as p
inner join `product-attribute` as pa on p.id = pa.product_id
inner join attribute as a on pa.attr_id = a.attr_id
這將返回一個簡單的結果表,您可以在其中創建多維數組。
您可能會在此查詢中注意到兩件事:
product-attribute
周圍使用反引號`
,因為它在名稱中包含一個破折號-
這是保留名稱。 因此,您需要將其放在反引號中以避開該名稱。 name
不明確,所以我給它們起了一個別名( product_name
/ attr_name
),以便以后仍可以用別名來引用它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.