高级选择

时间:2010-12-06 15:07:27

标签: mysql select join

我们有4张桌子:

mysql> desc Products;
+------------+-------------+------+-----+---------+----------------+
| Field      | Type        | Null | Key | Default | Extra          |
+------------+-------------+------+-----+---------+----------------+
| product_id | int(11)     | NO   | PRI | NULL    | auto_increment |
| product    | varchar(30) | NO   |     | NULL    |                |
+------------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> desc Vendors;
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| vendor_id | int(11)     | NO   | PRI | NULL    | auto_increment |
| vendor    | varchar(30) | YES  |     | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> desc Prices;
+------------+---------+------+-----+---------+----------------+
| Field      | Type    | Null | Key | Default | Extra          |
+------------+---------+------+-----+---------+----------------+
| price_id   | int(11) | NO   | PRI | NULL    | auto_increment |
| vendor_id  | int(11) | NO   | MUL | NULL    |                |
| product_id | int(11) | NO   | MUL | NULL    |                |
| price      | double  | YES  |     | NULL    |                |
+------------+---------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> desc Bought;
+------------+---------+------+-----+---------+----------------+
| Field      | Type    | Null | Key | Default | Extra          |
+------------+---------+------+-----+---------+----------------+
| bought_id  | int(11) | NO   | PRI | NULL    | auto_increment |
| product_id | int(11) | NO   | MUL | NULL    |                |
| date       | date    | YES  |     | NULL    |                |
| pieces     | int(11) | YES  |     | 1       |                |
+------------+---------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

现在我们需要一些复杂的select语句来获取我们需要的表:

第一个表需要列[供应商,产品,价格,供应商(提供产品)]。

第二张表应该显示$ date1和$ date2 [产品,件,供应商,价格,日期]之间购买的商品

上表应显示在给定时间内可以保存的内容[供应商(产品最便宜的供应商),产品,个人计算机,价格(适用于产品),总和(n个产品的价格)]。

由于这不会很复杂,因此生成的表必须显示名称,而不是键。我们坐在这个洞的日子里,但我们都没有人知道进行必要的搜索,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:0)

查看joins以从多个表中选择数据:

SELECT * FROM Prices LEFT JOIN (Vendors, Products)
                 ON (Products.product_id=Prices.product_id AND Vendors.vendor_id=Prices.vendor_id)