MYSQL从多个表中提取多个值

时间:2015-01-09 08:00:16

标签: mysql database many-to-many

请原谅我,我的头衔选择不当,我不确定该标题是什么,但我相信我可以解释一下。

我在产品表和商店表之间存在多对多的关系。

table name: products
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(200)     | NO   |     | NULL    |                |
| sku   | varchar(10)      | NO   |     | NULL    |                |
| units | int(5)           | YES  |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+

table name: stores
+----------+------------------+------+-----+---------+----------------+
| Field    | Type             | Null | Key | Default | Extra          |
+----------+------------------+------+-----+---------+----------------+
| id       | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| number   | int(5)           | NO   |     | NULL    |                |
| location | varchar(50)      | NO   |     | NULL    |                |
| phone    | varchar(10)      | YES  |     | NULL    |                |
+----------+------------------+------+-----+---------+----------------+


table name: products_stores
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| pID   | int(10) unsigned | NO   | PRI | NULL    |       |
| sID   | int(10) unsigned | NO   | PRI | NULL    |       |
+-------+------------------+------+-----+---------+-------+

我正在运行查询以显示商店中ID = 1

的所有商品
SELECT p.name, p.sku 
FROM products p 
  INNER JOIN products_stores ps
    ON p.id = ps.pID 
WHERE ps.sID = 1;

我对此查询没有任何问题,并获得我想要的结果。但是,在我的显示结果中,我还想显示每个结果行的商店位置值。我以为我可以在我的FROM语句中包含逗号分隔,例如:

SELECT p.name, p.sku, s.location
FROM products p, stores s
  INNER JOIN products_stores ps
    ON p.id = ps.pID
WHERE ps.sID = 1;

然而,这不起作用。我确信答案非常简单,我将继续研究解决方案。我想我会把它扔掉,希望有人能够带领我朝着正确的方向前进。

感谢。

2 个答案:

答案 0 :(得分:1)

SELECT 
  p.name,
  p.sku,
  s.location 
FROM
  products p,
  stores s,
  products_stores ps 
WHERE p.id = ps.pID 
  AND s.sID = ps.sID 
  AND ps.sID = 1 ;

答案 1 :(得分:1)

使用显式JOIN,不推荐使用JOIN(并且不太清楚)

SELECT p.name, p.sku ,s.location
FROM products p 
  INNER JOIN products_stores ps
    ON p.id = ps.pID 
INNER JOIN stores s
ON s.ID=ps.sID
WHERE ps.sID = 1;