这里是加载
mysql> drop database if exists luqita;
Query OK, 1 row affected (0.03 sec)
mysql> create database luqita;
Query OK, 1 row affected (0.01 sec)
mysql> use luqita
Database changed
mysql> create table countrydata
-> (
-> id int not null,
-> country varchar(32),
-> value int not null
->);
Query OK, 0 rows affected (0.10 sec)
mysql> insert into countrydata (id,country) values
-> (1,'Argelia' ),
-> (2,'USA' ),
-> (1,'China' ),
-> (1,'Italy' ),
-> (1,'Italy' ),
-> (1,'USA' ),
-> (4,'USA' ),
-> (1,'Argelia' );
Query OK, 8 rows affected, 1 warning (0.06 sec)
Records: 8 Duplicates: 0 Warnings: 1
mysql> select * from countrydata;
+----+---------+-------+
| id | country | value |
+----+---------+-------+
| 1 | Argelia | 0 |
| 2 | USA | 0 |
| 1 | China | 0 |
| 1 | Italy | 0 |
| 1 | Italy | 0 |
| 1 | USA | 0 |
| 4 | USA | 0 |
| 1 | Argelia | 0 |
+----+---------+-------+
8 rows in set (0.00 sec)
mysql>
伯爵只是意大利
select id,SUM(IF(country='Italy',1,0)) italy_count,COUNT(IF(id=1,1,0)) id_count
from countrydata WHERE id=1;
这里的样本数据对样本数据的查询
mysql> select id,SUM(IF(country='Italy',1,0)) italy_count,COUNT(IF(id=1,1,0)) id_count
-> from countrydata WHERE id=1;
+----+-------------+----------+
| id | italy_count | id_count |
+----+-------------+----------+
| 1 | 2 | 6 |
+----+-------------+----------+
1 row in set (0.00 sec)
mysql>
这里是所有包含查询
select B.*,
SUM(IF(A.country=B.country,1,0)) country_count,
SUM(IF(B.id=A.id,1,0)) id_count
from
countrydata A,
(select distinct id,country from countrydata) B
group by B.id,B.country;
这里是全包的查询执行
mysql> select B.*,
-> SUM(IF(A.country=B.country,1,0)) country_count,
-> SUM(IF(B.id=A.id,1,0)) id_count
-> from
-> countrydata A,
-> (select distinct id,country from countrydata) B
-> group by B.id,B.country;
+----+---------+---------------+----------+
| id | country | country_count | id_count |
+----+---------+---------------+----------+
| 1 | Argelia | 2 | 6 |
| 1 | China | 1 | 6 |
| 1 | Italy | 2 | 6 |
| 1 | USA | 3 | 6 |
| 2 | USA | 3 | 1 |
| 4 | USA | 3 | 1 |
+----+---------+---------------+----------+
6 rows in set (0.00 sec)
mysql>
你是如何创建很好格式化的表? – 2012-03-19 18:03:32
你有吗? – 2012-03-19 18:14:08
@I__:检查我的个人资料,我总是保持一些很酷的链接:) – 2012-03-19 18:19:47