I need to make an interface in which you can select each hardware / materiel part of many electronic devices :
In a table i'm storing all the devices :
:Name: :Id:
Computer 1
Laptop 2
Smartphone 3
... ...
I need to be able to associate different kind of materiel with them, by materiel i mean this table in which different items are stored :
:Name: :Id:
Keyboard 1
Screen 2
Mouse 3
Motherboard 4
Webcam 5
... ...
my problem is, for instance, that i need to associate the item Keyboard
with both computer
AND laptop
...
I already succeeded to associate items one by one, but because some devices got many items in common (like the keyboard) i need to be able to associate one item to all the devices i want.
So my question is simple: How can i store which item is associated with which device in a MySql database ?
Any hint there ?
EDIT :
Okay guys, so it seems that the Many-to-Many relation is the best way to do this, But anybody got some hint on how i should use sql queries to use the third table ? so i need to store for instance
:id1: :id2:
1 2
1 3
2 4
3 1
But is there simple sql commands to do such things or do i need to use heavy php scripting in order to do this ?
If I understand, it's a many to many relation.
So you need a another table for this relation. This table is called a junction table
This table would look like
DeviceID | MaterialID
And the primary key will be both columns.
So for the same Device, you can have many material and for the same material you can have many devices
Here's a good article about it
To insert your data. It's gonna be 3 basic insert into.
You need to insert in the device and material table first. Then you do the other insert in the junction table, cause you will have foreign key constraints on both field.
To select all devices with a keyboard you would do something like this
SELECT device.name FROM device INNER JOIN junctionTableName on device.id = junctionTableName.deviceId WHERE junctionTableName.materialId = yourkeyboardid
You need a JOIN
between the 2 tables. Here's an example where you know the keyboardID
but if you don't know it, you would have to do a subquery or a query before to select the id where name = keyboard
.
You will need a table to express this M:N relationship.
Like 'device_material' table, containing colums: device_id and material_id
You could use a third column in your second table
id item associate
-----------------------------
1 keyboard laptop
2 keyboard computer
3 mouse computer
4 webcam laptop
5 webcam computer
and then something like:
select * from devices_table d join accessory_table a on a.associate = d.name where foo = 'bar'