mysql - SQL查询从多个表中选择问题
问题描述
我有一个 mySQL 数据库,其中包含位于不同国家的学校在不同的汽车上提供培训(产品),目标不同。
SCHOOLS
id| schoolname |
----------------------------------
1 | Pete’s Driving school |
2 | Karen’s Driving school |
3 | John’s Driving school |
4 | Donald’s Driving school |
CARS
id| carbrand |
----------------------------------
1 | Buick |
2 | Mercedes |
3 | Tesla |
4 | Audi |
PROVIDES (PROVIDES THIS TRAINING)
id| name |
----------------------------------
1 | Get License |
2 | Practise driving |
3 | Maneuvering |
4 | Winter training |
LOCATIONS
id| name |
----------------------------------
1 | USA |
2 | UK |
3 | France |
4 | Japan |
我也有这些表格告诉我哪些学校有哪些汽车,哪些位置,并提供哪些培训:
SCHOOL_OWNS
id| schoolid | carsid
----------------------------------
1 | 1 | 2
2 | 1 | 1
3 | 2 | 1
4 | 3 | 2
SCHOOL_PROVIDES
id| schoolid | providesid
----------------------------------
1 | 1 | 2
2 | 1 | 3
3 | 2 | 1
4 | 3 | 2
SCHOOL_LOCATIONS
id| schoolid | locationsid
----------------------------------
1 | 1 | 2
2 | 2 | 4
3 | 2 | 1
4 | 3 | 2
我正在尝试选择和输出的产品..
PRODUCT
id| productname | schoolid | carid | locationid | price
----------------------------------
1 | Product1 | 2 | 1 | 4 | 400 USD
2 | Product2 | 3 | 1 | 2 | 300 USD
3 | Product3 | 1 | 2 | 1 | 200 USD
4 | Product4 | 2 | 2 | 1 | 100 USD
我现在的问题是如何编写一个 JOIN 查询来获得我正在寻找的东西。这让我很头疼,甚至不知道从哪里开始,或者我这样做的方式是否是推荐的设置方式?
我正在尝试创建一个 SQL 查询,让我可以根据汽车品牌、供应和位置这三个条件进行选择和排序。
我在页面顶部有三个下拉菜单“汽车”、“提供服务”和“位置”。
什么 SQL 查询可以匹配这两种情况?!谢谢。。有点迷路了。。
1. If I want to display all products that fulfill all
these three criteria (Buick, Maneuvering, Japan)
cars=1&provides=3&location=4
Output (only one product meet this criteria):
Product1 | Karen’s Driving school | 400 USD
-------------------
2. And if I only want display all products that provide ‘practise driving’ ?cars=&provides=2&location= ,
Then all products should show that have a company that provides “practice driving” ..
Output (only one two products meet this criteria):
Product1 | Karen’s Driving school | 400 USD
Product3 | John’s Driving school | 200 USD
解决方案
看起来您无法进行这些连接,因为您的表中没有外键。
例如..将汽车ID链接到提供ID将不起作用,因此无法轻松到达该表...您将需要一个外键或制作一个子表以使自己更容易!
推荐阅读
- powershell - cmdlet 无法运行,因为 -ContentType 参数不是有效的 Content-Type 标头
- laravel - Laravel year, sum, count, group by eloquent 查询
- python - Flask (Python) - 并行文件夹中图像的样式表 url_for 代码
- webpack - 如何在 VS Code Extension 中导入 wasm 文件?
- python - 如何从 Django 休息框架中相关字段的 to_representation 方法中返回一个 dict 对象?
- javascript - 如何根据角度 11 中的状态响应每 10 秒调用一次 API?
- excel - 坚持使用 VBA SumIf
- python - 随机异常排序字典列表(不排序)
- jboss - 打开资产时的 jBoss Business Central 错误消息
- ios - Apple Push APN 是否提供统计 API?