简体   繁体   English

MySQL计数类别中的项目

[英]MySQL Count Items In Category

I don't understand MySQL very well, here are the table structures I am using. 我不太了解MySQL,这是我正在使用的表结构。

users 用户

id | id | first_name | first_name | last_name | last_name | username | 用户名| password 密码

categories 类别

id | id | user_id | user_id | name | 名字| description 描述

links 链接

id | id | user_id | user_id | category_id | category_id | name | 名字| url | 网址| description | 描述| date_added | 添加日期| hit_counter hit_counter

I am trying to return a result set like this, to give information about the category for a user that includes how many links are in it. 我试图返回这样的结果集,以提供有关用户类别的信息,其中包括其中有多少个链接。

id | id | user_id | user_id | name | 名字| description | 描述| link_count LINK_COUNT

At the moment I have this query, but it only returns rows for categories that have links. 目前,我有此查询,但它只返回具有链接的类别的行。 It should return rows for categories that do not have any links (empty categories). 它应返回没有任何链接的类别的行(空类别)。

SELECT categories.*, COUNT(links.id) FROM categories LEFT JOIN links ON categories.id=links.category_id; 选择类别。*,从类别LEFT JOIN链接COUNT(links.id)链接到category.id = links.category_id;

How to do this query? 如何查询? Thanks. 谢谢。

we can't do select table dot "star" with an aggregate. 我们无法选择带有聚合的表点“星号”。

what you wanna do is something like (pseudocode): 您想要做的是(伪代码):

select
    categories.field1,
    categories.field2,
    {etc.}
    count(links.id)
from categories
left join links
    on categories.id = links.category_id
group by
    categories.field1,
    categories.field2,
    {etc.}

iow: you're missing the group by code-block to get the right aggregate in your query result set. iow:您缺少按代码分组的分组方式,无法在查询结果集中获得正确的汇总。

To mold alien052002's answer to fit your specific question, the following (untested) should work: 为了使Alien052002的答案适合您的特定问题,以下(未经测试)应该起作用:

select c.id,
    c.user_id,
    c.name,
    c.description,
    count(l.link_count)
from categories c
left join links l on l.category_id = c.id
group by c.id, c.user_id, c.name, c.description

尝试这个

SELECT categories.*, COUNT(links.id) FROM categories LEFT JOIN links ON categories.id=links.category_id group by categories.id;

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

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