简体   繁体   English

SQL子集查询

[英]SQL subsets query

I am having trouble creating a query for an SQL table. 我在为SQL表创建查询时遇到问题。 The query I am trying to create shows the number of products within the category of "clothes" and does not show accessories for example a list of products that are entered as T-shirts or sweatshirts. 我尝试创建的查询显示“衣服”类别中的产品数量,而不显示配件,例如输入为T恤或运动衫的产品列表。

Here is the tables that have been created: 这是已创建的表:

CREATE DATABASE IF NOT EXISTS product_list;

DROP TABLE IF EXISTS products;
DROP TABLE IF EXISTS product_categories;
DROP TABLE IF EXISTS categories;

CREATE TABLE products (
    product_id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(50) DEFAULT NULL,
    active BOOL DEFAULT NULL
);

CREATE TABLE categories (
    category_id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50),
    structure VARCHAR(50)
);

CREATE TABLE product_categories (
    product_id INT,
    category_id INT,
    PRIMARY KEY(product_id, category_id)
);

INSERT INTO products VALUES
(NULL, "Blue Sweatshirt", false),
(NULL, "Short Sleeve T-Shirt", true),
(NULL, "White Vest", true),
(NULL, "Black Hairclip", true),
(NULL, "Knitted Hat", false),
(NULL, "Grey Sweatshirt", true),
(NULL, "Tartan Scarf", true);

INSERT INTO categories VALUES
(NULL, "Sweatshirts", "Clothes>Sweatshirts"),
(NULL, "T-Shirts", "Clothes>T-Shirts"),
(NULL, "Accessories", "Accessories"),
(NULL, "Winter", "Clothes>Winter"),
(NULL, "Vests", "Clothes>Vests");

INSERT INTO product_categories VALUES
(1, 1), (2, 2), (3, 5), (3, 4), (4, 3), (5, 3), (5, 4), (6, 1), (7, 3), (7, 4);

If I understand correctly, this is a set-within-sets query. 如果我理解正确的话,这是组内查询。 You are looking for products that have at least one "clothes" category, and none of the categories are not clothes. 您正在寻找的商品至少具有一个“衣服”类别,并且所有类别都不是衣服。 I approach this using group by and having because it is quite flexible: 我使用group by进行处理having因为它非常灵活:

select pc.product_id
from Product_categories pc join
     categories c
     on pc.category_id = c.category_id
group by pc.product_id
having sum(case when c.structure like 'Clothes%' then 1 else 0 end) > 0 and
       sum(case when c.structure not like 'Clothes%' then 1 else 0 end) = 0;

If you just want the count, then you can use this as a subquery and use count(*) . 如果只需要计数,则可以将其用作子查询并使用count(*)

EDIT: 编辑:

A small note. 一个小笔记。 The question is now tagged with MySQL, which has convenient short-hand for the having clause: 现在,该问题已使用MySQL进行了标记,它having Have子句的便捷缩写:

having sum(c.structure like 'Clothes%') > 0 and
       sum(c.structure not like 'Clothes%') = 0;

Try this query 试试这个查询

select * from products a
join Product_categories b on a.product_id=b.product_id
join categories c on b.category_id=b.category_id
where c.name like '%Clothes%'

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

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