sql 基础--mysql 5 (7)

14.高级联结表

  使用别名

mysql> select uid as u,name as n,msg as m from pw_luck;
+----+-----------+------+
| u  | n         | m    |
+----+-----------+------+
|  0 | Wilson    |  100 |
|  1 | zhangsan  |  100 |
|  2 | lisi      | 1001 |
|  3 | wang5     | 1001 |
|  7 | zhangsan7 | 1000 |
|  8 | zhangsan8 | 1000 |
|  9 | zhangsan9 | 1000 |
| 10 | wang5     | 1000 |
| 11 | wang5%    | 2000 |
| 12 | WANG5     | 1000 |
| 13 | wang5     |  100 |
| 14 | wang5     |  100 |
| 15 | zhangsan7 | 1000 |
| 16 | zhangsan7 | 1002 |
| 17 | zhangsan7 | 1002 |
+----+-----------+------+
15 rows in set (0.03 sec)

 自联结

mysql> select uid,name,msg from pw_luck where msg=(select msg from pw_luck where uid=0);
+-----+----------+-----+
| uid | name     | msg |
+-----+----------+-----+
|   0 | Wilson   | 100 |
|   1 | zhangsan | 100 |
|  13 | wang5    | 100 |
|  14 | wang5    | 100 |
+-----+----------+-----+
4 rows in set (0.00 sec)
mysql> select uid,name,msg from pw_luck where msg  in (select msg from pw_luck where uid=0);
+-----+----------+-----+
| uid | name     | msg |
+-----+----------+-----+
|   0 | Wilson   | 100 |
|   1 | zhangsan | 100 |
|  13 | wang5    | 100 |
|  14 | wang5    | 100 |
+-----+----------+-----+
4 rows in set (0.00 sec)

外联结

mysql> select pw_luck.uid,pw_luck.name,pw_luck.msg,pw_price.price from pw_luck,pw_price where msg i
 (select msg from pw_luck where pw_luck.uid=pw_price.uid) and pw_luck.uid=1;
+-----+----------+-----+-------+
| uid | name     | msg | price |
+-----+----------+-----+-------+
|   1 | zhangsan | 100 |   100 |
+-----+----------+-----+-------+
1 row in set (0.00 sec)

带聚集函数的联结

mysql> select pw_luck.uid,pw_luck.msg,pw_price.price from pw_luck,pw_price where msg in (select msg
from pw_luck where pw_luck.uid=pw_price.uid);
+-----+------+-------+
| uid | msg  | price |
+-----+------+-------+
|   0 |  100 |   100 |
|   1 |  100 |   100 |
|   2 | 1001 |  1000 |
|   2 | 1001 |  2000 |
|   3 | 1001 |  1000 |
|   3 | 1001 |  2000 |
|  13 |  100 |   100 |
|  14 |  100 |   100 |
+-----+------+-------+
8 rows in set (0.00 sec)

mysql> select pw_luck.uid,pw_luck.msg,sum(pw_price.price) as pricesum from pw_luck,pw_price where ms
g in (select msg from pw_luck where pw_luck.uid=pw_price.uid) group by uid;
+-----+------+----------+
| uid | msg  | pricesum |
+-----+------+----------+
|   0 |  100 |      100 |
|   1 |  100 |      100 |
|   2 | 1001 |     3000 |
|   3 | 1001 |     3000 |
|  13 |  100 |      100 |
|  14 |  100 |      100 |
+-----+------+----------+
6 rows in set (0.00 sec)

 

posted on 2015-02-26 11:42  wjw334  阅读(211)  评论(0编辑  收藏  举报

导航