我不是DBA,但仍在努力弄清楚如何解决以下问题。 我正从DB中检索各类动物的数量。 现在,从具有多个连接的查询中检索计数后,我得到所有计数(在总计数列中提到) 但我想用两个代表类型和描述的列来表示该数据。但我无法做到这一点。 就像,我从一个有连接的查询得到总计数我希望将这些计数显示为
Type_of_animal|description |total_count
------------- |---------------------------------------|-----------
Reptiles |Reptiles are cold-blooded vertebrates | 5000
Mammals |People are mammals | 80000
Birds |Any which have feathers | 1000000
我希望通过手动命名type_of_animal来表示这些计数,并将其描述视为针对每个计数。
一个查询是
SELECT count(catmang.category_id) AS 'Total Counts'
FROM category catmang
JOIN category_identifier catident ON catident.category_id = catmang.category_id
WHERE category_id = 5
答案 0 :(得分:0)
SELECT category_identifier.*, COUNT(*) as total_count
FROM category_identifier
LEFT JOIN category using(category_id)
GROUP BY category_identifier.category_id
(可能使用category_identifier。*交换.type和.description)
<强>更新强>
因为原始海报并不想使用实际存在于数据库中的数据(从数据库中获取所有数据),所以&#34;虚拟&#34;表可以创建,但它非常冗长和烦人。添加此联接:
LEFT JOIN (
SELECT 'Reptiles' as Type_of_animal,
'Reptiles are cold-blooded vertebrates' as description,
1 as category_id
UNION
SELECT 'Mammals' as Type_of_animal,
'Reptiles are cold-blooded vertebrates' as description,
2 as category_id
UNION
.......
) as texts USING(category_id)
并在select中使用texts.type_of_animal,texts.description。你必须修改category_ids ......