返回主类别中的报价总和

svdrlsy4  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(466)

我正在努力从特定的主类别返回提供的总和(主类别是一个没有父\ id。主类别包括许多子类别)。
类别表:

CREATE TABLE `category` (
    `id` int PRIMARY KEY AUTO_INCREMENT,
    `name` varchar(255) NOT NULL,
    `parent_id` int,
    `slug` varchar(255) NOT NULL unique,
    `created_at` datetime NOT NULL,
    `updated_at` datetime NOT NULL,
    `active` boolean NOT NULL default 1
);

报价表:

CREATE TABLE `offer` (
    `id` int PRIMARY KEY AUTO_INCREMENT,
    `user_id` int NOT NULL,
    `category_id` int NOT NULL,
    `slug` varchar(255) NOT NULL unique,
    `title` varchar(255) NOT NULL,
    `description` varchar(1000) NOT NULL,
    `budget` int NOT NULL,
    `remote` boolean NOT NULL,
    `email` varchar(255) NOT NULL,
    `phone` varchar(255),

    `pub_date` datetime NOT NULL,
    `exp_date` datetime NOT NULL,

    `sent_at` datetime NOT NULL,

    `created_at` datetime NOT NULL,
    `updated_at` datetime NOT NULL,
    `active` boolean NOT NULL default 1
);

此查询返回包含该子类别中offer count的所有子类别。我想完成的是,它也将是一个类似“父\提供”的列,其中将是指定主类别的所有子类别中所有提供的值

SELECT c.id, c.name, c.slug, parent.name AS `parent_name`, parent.id AS `parent_id`, parent.slug as 'parent_slug', COUNT(o.id) as cat_offers
FROM category AS c
JOIN category AS parent ON parent.id = c.parent_id
LEFT JOIN offer o ON c.id = o.category_id
WHERE c.active = true
GROUP BY c.id
ORDER BY parent.name, c.name ASC

我试图完成的图形示例:

|---------------------|--------------|-----------------|--------------|
|      parent_cat     |   category   | cat_offers      | parent_offers|
|---------------------|--------------|-----------------|--------------|
|          10         |      31      |      7          |       16     |
|---------------------|--------------|-----------------|--------------|
|          10         |      32      |      2          |       16     |
|---------------------|--------------|-----------------|--------------| 
|          10         |      33      |      6          |       16     |
|---------------------|--------------|-----------------|--------------| 
|          10         |      34      |      1          |       16     |
|---------------------|--------------|-----------------|--------------|

已经尝试加入第二次提供表与其他条件,试图做不同的子选择,没有工人为我。感觉我好像在转啊转。

00jrzges

00jrzges1#

我想你需要做一个子查询。前任。:

SELECT c.id, c.name, c.slug, parent.name AS `parent_name`, 
parent.id AS `parent_id`, parent.slug as 'parent_slug', 
    (SELECT COUNT(o.*) FROM offer o WHERE c.id = o.category_id) as cat_offers
        FROM category AS c
        JOIN category AS parent ON parent.id = c.parent_id
        WHERE c.active = true
        GROUP BY c.id
        ORDER BY parent.name, c.name ASC

相关问题