我是sql的新手,并且已经设法通过下面的sql选择与许多表相关的行。我现在有一张第四张桌子,上面列出了该模型的“子项”。模型表中的“ id”(526行)和项目表中的“ model_id”(1505行)之间存在关联。现在,我要计算项目表中与模型表中的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
谢谢!
答案 0 :(得分:0)
您的目标不是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