gpt4 book ai didi

mysql - SQL 连接和 MySQL

转载 作者:行者123 更新时间:2023-12-01 00:13:34 25 4
gpt4 key购买 nike

在我的数据库中我有这些表

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 的数据

我做错了什么?

最佳答案

您没有告诉查询将什么加入 productsproducts_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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com