I'm working on a small project, and i wanted to create a table, like the one in the image des

Question:

Is there any way to create a table like this in python and MySQL?

image description here

Asked By: Thakshaya

||

Answers:

Before that let’s just think of the Database choices, the image you have shown have the following structure.

column_one column_two column_three
value_a_0 value_a_1_0, value_a_1_1 value_a_2
value_b_0 value_b_1_0, value_b_1_1 value_b_2

I am using commas(,) to show the divide in the second column. Now such columns or data is called a denormalized data. A type such as an Array would be great. In such a case Postgres would be a good choice.

A good way to go around this is to use relations (exactly what relational databases are made for), I would also suggest creating a fourth column that uses something like an AUTO INCREMENT for Primary Key.

-- I am placing TEXT as datatypes but I would suggest you to pick your datatypes well
CREATE TABLE `table_one` (
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `column_one` TEXT,
    `column_two` INT,
    `column_three` TEXT,
    CONSTRAINT `table_one_two_fk` FOREIGN KEY (`column_two`) REFERENCES `table_two` (`id`)
);
CREATE TABLE `table_two` (
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `column_value` TEXT
);

This will relationally store those values, therefore for fetching the data you can possibly do something like this:

SELECT *
FROM `table_one`
INNER JOIN `table_two` ON `table_one`.`column_two` = `table_two`.`id`;
Answered By: frostzt
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.