[英]How to select dependent columns from a single table in MySQL
I have products_table like this: 我有这样的products_table:
prod_ID (int)
, sub_of (int)
, category (int)
, price (decimal 10,2)
, sort (int)
prod_ID (int)
, sub_of (int)
, category (int)
, price (decimal 10,2)
, sort (int)
Main products has sub_of set to 0, category set to some id from other table and no price set. 主要产品的sub_of设置为0,类别设置为其他表的某些ID,并且未设置价格。 only sub products has price, but no category. 只有子产品有价格,但没有类别。
My english is bad, so I'll try to ask the question with SQL: 我的英语不好,所以我尝试用SQL提问:
I want to 我想要
SELECT *
FROM products_table
WHERE category IN (3, 158, 159, 160, 249)
AND sub_of = 0
AND price >= 27
AND price <= 34
ORDER BY sort+0, sort
How can I do this? 我怎样才能做到这一点?
I'm tring with SELECT in SELECT but does not select correct prices: 我在SELECT中尝试SELECT,但未选择正确的价格:
$where = ajax: AND price >= 27 AND price <= 34
$daOrder = SORT BY sort+0, sort
$query = "SELECT *
FROM ".PRODUCTS_TABLE."
WHERE prod_ID IN (
SELECT sub_of
FROM ".PRODUCTS_TABLE."
WHERE sub_of IN (
SELECT prod_ID
FROM ".PRODUCTS_TABLE."
WHERE category IN (".$allCats.")
)
".mysql_escape_string($where)." {$daOrder}
)";
Edit: 编辑:
I need all main products (sub_of=0) from some categories and with price range, then I will list all sub products of each main product. 我需要某些类别和价格范围内的所有主要产品(sub_of = 0),然后列出每个主要产品的所有子产品。
I would go for a self-join: 我会寻求自我加入:
SELECT *
FROM products_table as main_products
LEFT JOIN products_table as sub_products
ON sub_products.sub_of = main_products.prod_id
WHERE main_products.category IN (3, 158, 159, 160, 249)
AND sub_products.price >= 27
AND sub_products.price <= 34
ORDER BY sub_products.sort
Your question still leaves room for interpretation. 您的问题仍然有解释的余地。
This gives you all main-products of the the chosen categories where all sub-products are within the given price range (none cheaper or more expensive): 这将为您提供所选类别的所有主要产品 ,其中所有子产品均在给定的价格范围内(没有更便宜或更昂贵的价格):
SELECT m.*
FROM products_table m
JOIN (
SELECT sub_of AS prod_id
FROM products_table p
WHERE p.category IN (3, 158, 159, 160, 249)
GROUP BY 1, p.category -- only useful if there are multiple cat. per main-prod
HAVING min(price) >= 27
AND max(price) <= 34
) p USING (prod_id)
WHERE m.sub_of = 0 -- should be redundant if your data model is clean
ORDER BY m.sort + 0, m.sort; -- copied the weird ORDER BY verbatim
Accordingly, this returns all sub-products belonging to the main-products above: 因此,这将返回属于上述主要产品的所有子产品:
SELECT s.*
FROM products_table s
JOIN (
SELECT sub_of
FROM products_table p
WHERE p.category IN (3, 158, 159, 160, 249)
GROUP BY 1, p.category
HAVING min(price) >= 27
AND max(price) <= 34
) p USING (sub_of)
WHERE s.sub_of <> 0 -- should be redundant if your data model is clean
ORDER BY s.sort + 0, s.sort; -- copied the weird ORDER BY verbatim
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.