多表查询时,要给表名起别名,给字段名其别名(当两个表含有重复字段时)
select p.name, c.name, pid from products p, cats c;//得到的结果为笛卡尔乘积
- select p.name as pname, p.price, p.desn, p.num from products p, cats c where c.id = p.cid ;//查询所有商品属于哪个分类
- select p.name as pname, p.price, p.desn, p.num from products p, cats c where c.id = p.cid and c.name like '%java%'//查询类名中含有java的商品信息
-
mysql> select * from cats;
+----+-----+-------+-----------+
| id | pid | name | desn |
+----+-----+-------+-----------+
| 4 | 0 | soft | this soft |
| 5 | 4 | java | this java |
| 6 | 4 | php | this java |
| 7 | 4 | c++ | this java |
| 8 | 5 | j2ee | j2ee |
| 9 | 5 | j2me | j2me |
| 10 | 9 | j2me1 | j2me1 |
+----+-----+-------+-----------+ -
mysql> select a.id aid, a.name aname, b.id bid, b.name bname from cats a, cats b where a.pid = b.id;//查询所有分类
+-----+-------+-----+-------+
| aid | aname | bid | bname |
+-----+-------+-----+-------+
| 7 | c++ | 4 | soft |
| 8 | j2ee | 5 | java |
| 9 | j2me | 5 | java |
| 10 | j2me1 | 9 | j2me |
| 5 | java | 4 | soft |
| 6 | php | 4 | soft |
+-----+-------+-----+-------+
6 rows in set (0.00 sec)