Your second approach is the right direction. This is clear from the first line of your question: "I want to represent a device who posses a led screen, a bunch of sensors, and some other properties." You have three different entities in the real world. Model them as three different entities.
Room for improvement. Use auto-incremented integer primary keys for the ids. I also prefer calling the id
after the name of the table, so DeviceId
is the primary key for that. That means that any join is "obvious" because the join fields are named the same or very similarly.
In addition, I think you need additional tables for Sensors
and possibly LED
s. That is, the type
information should be stored in a different table.
Here is my suggestion:
CREATE TABLE Devices (
DeviceID int not nullauto_increment primary key
Name varchar(32) NOT NULL UNIQUE,
Owner_UserId int NOT NULL,
FOREIGN KEY (Owner_UserId) REFERENCES users(Userid)
);
create table Sensors (
SensorId int not null auto_increment primary key,
Type int,
Name varchar(255)
);
CREATE TABLE sensors (
DeviceID int NOT NULL,
SensorID int not null,
status BOOL,
data REAL,
primary key (DeviceID, SensorId)
foreign key (DeviceID) REFERENCES devices(DeviceID),
foreign key (SensorId) REFERENCES sensors(SensorID),
);
CREATE TABLE leds (
DeviceID int not null,
value varchar(6) NOT NULL,
x INT(3) NOT NULL,
y INT(3) NOT NULL,
PRIMARY KEY (DeviceID, x, y),
FOREIGN KEY (DeviceID) REFERENCES devices(DeviceID)
);
In general, when creating tables, I also add two or three default columns at the end:
CreatedAt . . . the date/time when created (a timestamp column in MySQL)
CreatedBy . . . who created the column
CreatedOn . . . The server where the machine was created (if the system is going to span servers)