mysql - 在mysql中使用关系时如何获取行数
问题描述
我是 sql 的新手,我已经设法使用下面的 sql 选择与许多表有关系的行。我现在有第四张表,其中包含模型的“子项”项目。模型表(526 行)中的“id”和项目表(1505 行)中的“model_id”之间存在关系。我现在想计算 items 表中与模型表中的 id 具有相同 model_id 的项目,并将它们输出为 Items_in_model。
SELECT models.id AS Id, categories.name AS Category, models.category_name
AS CategoryName, manufacturers.name AS Manufacturer, models.model AS Model,
models.day_price AS dayprice, models.week_price AS weekprice
FROM
models, categories, manufacturers
WHERE models.category=categories.id AND
models.manufacturer=manufacturers.id
ORDER BY CategoryName ASC
我用这个 sql 让计数工作“独立”
SELECT COUNT(items.id) AS Count FROM items WHERE items.model_id
LIKE 2
我尝试了许多不同的方法,但这是唯一没有给我错误但只输出一行(共 526 行)并且计数为(所有项目中为 1505)的方法
SELECT models.id AS Id, categories.name AS Category,
models.category_name AS CategoryName, COUNT(items.id) AS Count,
manufacturers.name AS Manufacturer, models.model AS Model,
COUNT(DISTINCT(items.id)) AS ModelCount, models.day_price AS dayprice,
models.week_price AS weekprice
FROM
models, categories, manufacturers, items
WHERE models.category=categories.id AND
models.manufacturer=manufacturers.id AND models.id=items.model_id
ORDER BY CategoryName ASC
提前致谢!
解决方案
您的目标不是 100% 明确,但这是我的猜测:
SELECT m.id AS Id,
c.name AS Category,
m.category_name AS CategoryName,
manufacturers.name AS Manufacturer,
m.model AS Model,
COUNT(i.id) AS ModelCount,
m.day_price AS dayprice,
m.week_price AS weekprice
FROM models m
LEFT JOIN categories c
ON m.category=c.id
LEFT JOIN manufacturers
ON m.manufacturer=manufacturers.id
LEFT JOIN items i
ON m.id=i.model_id
GROUP BY m.id
更新不确定您的新问题,但我怀疑您是否需要额外的JOIN
. 试试这个方法:
SELECT m.id AS Id,
c.name AS Category,
m.category_name AS CategoryName,
manufacturers.name AS Manufacturer,
m.model AS Model,
COUNT(i.id) AS ModelCount,
SUM(IF(i.reservable = 1,1,0)) AS ModelReservableCount,
m.day_price AS dayprice,
m.week_price AS weekprice
FROM models m
LEFT JOIN categories c
ON m.category=c.id
LEFT JOIN manufacturers
ON m.manufacturer=manufacturers.id
LEFT JOIN items i
ON m.id=i.model_id
GROUP BY m.id
推荐阅读
- python - 获取 TypeError:预期的 str、bytes 或 os.PathLike 对象,而不是 InMemoryUploadedFile
- oracle - 从 Oracle 到 Cassandra 的 DBLink
- php - 从数据库中读取数据并在 Google Charts 中显示
- android - 如何以编程方式在android中获取没有触摸事件的视图的x,y坐标?
- python - pandas groupby hour 并计算缺货时间
- javascript - 这两种处理顺序 Promise 的风格有什么区别
- php - 安装 PHP 7.2 扩展 pdflib,模块错误
- laravel - 查询对象字段中的所有属性
- node.js - Mongoose:通过传递变量查找
- sql - 更新 postgreSQL 首字母大写中的列