MySQL联接查询 [英] MySQL Join Query
问题描述
我需要为以下内容创建一个联接查询:
I need to create a join query for the following:
表供应商:
- id
- 名称
表Supplier_vehicles
Table supplier_vehicles
- id
- supplier_id
- vehicle_id
一个供应商可以拥有多辆车.
A supplier can have multiple vehicles.
在我的前端表单上,我有一个复选框列表-用户可以选择多辆车.后端脚本需要进行搜索,并带回所有包含任何指定车辆ID的供应商.
On my front-end form I have a checkbox list - a user can select multiple vehicles. The back end script needs to do a search and bring back all suppliers that contain any of the specified vehicle id's.
复选框列表名称为vehicle_type [],将最终出现在$ _POST数组中,例如:
The checkbox list name is vehicle_type[] and will end up in the $_POST array as (for example):
Array
(
[0] => 1
[1] => 4
[2] => 6
)
目前,我可以使用一些SQL示例,以便可以使用不同的值测试查询.
At the moment I could do with with some SQL examples so that I can test the query using different values.
推荐答案
如果知道车辆ID,则可以使用IN子句:
If you know the vehicle ID's, you can use an IN clause:
SELECT *
FROM supplier s
, supplier_vehicles v
WHERE s.id = v.supplier_id
AND v.vehicle_id IN (1, 4, 6)
如果只需要唯一的供应商ID,则可以使用DISTINCT.
If you just want the distinct supplier ID's, you could use DISTINCT.
SELECT DISTINCT s.supplier_id
FROM supplier s
, supplier_vehicles v
WHERE s.id = v.supplier_id
AND v.vehicle_id IN (1, 4, 6)
这篇关于MySQL联接查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!