SELECT t.id_type, brand, model, countMod FROM types t
LEFT JOIN (
SELECT p.id_type, brand, model, COUNT( model ) AS countMod
FROM products p
GROUP BY brand) p2
ON t.id_type = p2.id_type
WHERE t.id_type = "TCE"
ORDER BY brand
此查询工作正常,但我丢失了在每个品牌下分组的模型
有没有办法列出并计算模型?
即brand1,model1,model2,model3,countMod = 3 - brand2,model1,model2,countMod = 2。
任何帮助将不胜感激。感谢
答案 0 :(得分:2)
SELECT brand, GROUP_CONCAT(model) models, COUNT(model) AS countMod
FROM products
GROUP BY brand
答案 1 :(得分:1)
试试这个::
SELECT
t.id_type,
brand,
GROUP_CONCAT(model SEPARATOR ',') as model,
COUNT( model ) AS countMod
FROM types t
LEFT JOIN products p ON t.id_type = p.id_type
WHERE t.id_type = "TCE"
GROUP BY brand
ORDER BY brand
答案 2 :(得分:-1)
推荐的方法是运行两个查询,一个用于数据,另一个用于COUNT()
。
使用MySQL,你也可以使用SQL_CALC_FOUND_ROWS
(主要是你有一个LIMIT
子句),但是它的表现是有争议的,请参阅Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)。