问题
I have a question how to make the right sql statement, because I have no Idea how to start ;-(
There are the following two tables:
Table 1: test
id|name|type
-------------
1|FirstUnit|1
2|FirstWeb|2
3|SecondUnit|1
Table 2: types
id|type
--------
1|UnitTest
2|WebTest
I would like to get the following result:
Table result:
type|amount
-----------
UnitTest|2
WebTest|1
Can anyone helping with giving a hint how to start?
Thanks in advance. LStrike
回答1:
You can try this query:
SELECT
t.type ,
COUNT(*) AS amount
FROM types AS t
JOIN test AS te ON t.id= te.type
GROUP BY type
ORDER BY t.type
回答2:
SELECT a.type, COUNT(b.type) amount
FROM types a
LEFT JOIN test b
ON a.ID = b.type
GROUP BY a.type
ORDER BY amount DESC
- SQLFiddle Demo
To further gain more knowledge about joins, kindly visit the link below:
- Visual Representation of SQL Joins
回答3:
Here is the solution:-
SELECT types.type, COUNT(test.type) as amount from types,test where test.type=types.id
GROUP BY test.type
ORDER BY amount
来源:https://stackoverflow.com/questions/15807635/sql-count-over-2-tables-by-a-type