简体   繁体   English

MYSQL-SELECT产品的parent_category处于活动状态

[英]MYSQL - SELECT products WHERE parent_category is active

assuming we have a database category structure like this 假设我们有这样的数据库类别结构

# Categories Table
| category_id | parent_category_id | status |

# Products Table
| product_id | category_id |

how do i get the list of products in a category only if the parent_category_id has an active status = 1 ? 仅当 parent_category_id的活动status = 1如何才能获得类别中的产品列表?

i guess i could use some sub-query in the SELECT statement, but i don't know how! 我想我可以在SELECT语句中使用一些子查询,但是我不知道怎么做! :( :(

something like: 就像是:

SELECT p.*, (SELECT * FROM ? WHERE ? ) AS x 
FROM products AS p 
    LEFT JOIN categories AS c ON p.category_id = c.category_id 
WHERE ... 
AND p.product_id = '?' 
AND ...

Thank you in advance for any advice! 预先感谢您的任何建议!

NB: i'm using PHP as backend language, just in case i need some sort of data manipulation to pass to the mysql query. 注意:我使用PHP作为后端语言,以防万一我需要某种数据处理才能传递给mysql查询。

try not to use subquery, because it can affect the speed of loading data 尽量不要使用子查询,因为它会影响加载数据的速度

maybe it can help 也许可以帮上忙

SELECT *
FROM categories c
INNER JOIN products p ON p.category_id=c.category_id
WHERE c.status = 1
SELECT p.* FROM products p
INNER JOIN categories child ON child.category_id = p.category_id
INNER JOIN categories parent ON parent.category_id = child.parent_category_id
WHERE parent.status=1

Here a example query, I don't use left join or join, becasue you require that the record exists in order to get the status. 在此示例查询中,我不使用左联接或联接,因为您需要该记录存在才能获取状态。

SELECT 
   *
FROM
   products, categories
WHERE
   products.category_id = categories.category_id
   AND status = '1'

First you have to get all active categories 首先,您必须获得所有活动类别

SELECT child.*
FROM Categories child
JOIN Categories parent
  ON child.parent_category_id = parent.category_id 
 AND parent.status = 1

But you also need the root categories with not parent_id 但是您还需要不带有parent_id的根类别

SELECT *
FROM Categories
WHERE parent_category_id IS NULL
  AND status = 1

So you UNION both 所以你们两个都

SELECT *
FROM Categories child
JOIN Categories parent
  ON child.parent_category_id = parent.category_id 
 AND parent.status = 1

UNION ALL

SELECT *
FROM Categories
WHERE parent_category_id IS NULL
  AND status = 1

Now you get the products for those categories 现在您获得了这些类别的产品

SELECT *
FROM (  ... UNION ALL ... ) active_categories
JOIN Products
 ON active_categories.category_id = Product.category_id 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM