在我的数据库中我有这些表
products
-------------
id | title |
-------------
1 Cheese
2 Milk
3 Water
等......
products_to_city
-----------------------
city_id | product_id |
-----------------------
1 1
1 2
2 3
3 1
3 1
我正在使用这个 sql 查询来获取结果
SELECT
p.id,
p.title
FROM products p
LEFT JOIN products_to_city ptc ON ptc.id = 1
问题是上面的查询从表中获取所有数据,而不是只获取城市为 1 的数据
我做错了什么?
最佳答案
您没有告诉查询将什么加入 products
和 products_to_city
。尤其是 LEFT JOIN
,它会强制结果集包含 products
中的每条记录,以及 products_to_city
中的每条记录。我想你想要这个:
SELECT p.id, p.title
FROM products p
INNER JOIN products_to_city ptc
ON p.id = ptc.product_id
WHERE
ptc.city_id = 1
关于mysql - SQL 连接和 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10818305/