我是一个sql的新手,我已经设法选择与许多表有关系的行与下面的sql。我现在有一个第四个表格,其中的项目是模型的“孩子”。模型表(526行)中的“id”和项目表(1505行)中的“model_id”之间存在关系。我现在想要计算items表中与models表中的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