简体   繁体   English

MySQL-在多值字段中搜索

[英]MySQL - Searching in a multiple value field

In my database table I have the following fields: 在我的数据库表中,我具有以下字段:

Table Supplier: 表供应商:

  • id ID
  • name 名称
  • vehicles 车辆

A supplier can have multiple vehicles. 供应商可以有多辆车。 The field 'vehicles' will store multiple values. “车辆”字段将存储多个值。 At the moment I am delimiting the values on a 'pipe' symbol, although this can be changed to a comma if need be. 目前,我正在划定“管道”符号上的值,尽管如果需要可以将其更改为逗号。

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. 后端脚本需要进行搜索,并带回包含任何指定车辆ID的所有供应商。

So in other words we are searching with multiple values in a multiple value field. 因此,换句话说,我们正在多值字段中搜索多个值。

The checkbox list name is vehicle_type[] and will end up in the $_POST array as (for example): 复选框列表名称为vehicle_type [],将最终出现在$ _POST数组中,例如:

Array 
( 
    [0] => 1 
    [1] => 4 
    [2] => 6 
)

Is this possible to do? 这可能吗? I could obviously do this using a join table but ideally I would like to do it this way. 我显然可以使用联接表来执行此操作,但理想情况下,我想这样做。 I am using PHP as my scripting language if that helps. 如果有帮助,我正在使用PHP作为脚本语言。

The field 'vehicles' will store multiple values. “车辆”字段将存储多个值。 At the moment I am delimiting the values on a 'pipe' symbol, although this can be changed to a comma if need be. 目前,我正在划定“管道”符号上的值,尽管如果需要可以将其更改为逗号。

Please don't do that. 请不要这样做。 Storing delimited data in a text field is no better than storing it in a flat file . 将分隔的数据存储在文本字段中并不比将其存储在平面文件中更好 The data becomes unqueryable. 数据变得不可查询。

You want a nice, happy, normalized database . 您需要一个不错的,快乐的,规范化的数据库

CREATE TABLE Suppliers (
    supplier_id INTEGER PRIMARY KEY,
    ...
);

CREATE TABLE Vehicles (
    vehicle_id INTEGER PRIMARY KEY,
    ...
);

CREATE TABLE Supplier_Vehicles (
    supplier_id INTEGER NOT NULL REFERENCES Suppliers(supplier_id),
    vehicle_id INTEGER NOT NULL REFERENCES Vehicles(vehicle_id),
    UNIQUE KEY(supplier_id, vehicle_id)
);

-- Grab all the Vehicles for Supplier 39
SELECT Vehicles.*
  FROM Vehicles, Supplier_Vehicles
 WHERE Supplier_Vehicles.supplier_id = 39
   AND Supplier_Vehicles.vehicle_id = Vehicles.vehicle_id

The checkbox list name is vehicle_type[] and will end up in the $_POST array as (for example) [...] Is this possible to do? 复选框列表名称为vehicle_type [],并以$ _POST数组结尾(例如)[...]这可能吗?

It's very possible, and is a good idea. 这很有可能,也是个好主意。 Try it and find out how well it works. 尝试一下,找出其效果如何。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM