Structuring MySQL table (infinite amount columns) - php

like title says, I'm wondering how you can structure a mySQL table to be able to add infinite (or high, ≈1000) amount columns.
Basically, I want a table containing column with school classes. Each class has some students in it with their name and last name. The structure I want it something like this:
-----Class 1-----------
Lastname-Surname
1. Michel Ericsson
2. Erica Bloom
....
-----Class 2-----------
Lastname-Surname
1. Fred Jackson
2. Erica Hancock
....
......

I think what you want to do is create a Many to Many relation between a "Class" table and your "Student" table. For example you have a table
Class
id: int (primary key auto-incremented)
name: varchar
And another table :
Student
id: int (primary key auto-incremented)
name: varchar
surname: varchar
And then, you need a table that will be the link between these previous two :
Class_student
class_id: int (primary key)
student_id: int (primary key)
This way you can link as many Students to as many classes you want.

Related

Laravel: fetch pivot relationship through another relationship

Using Laravel, I'd like to fetch an order status (order_status table) from an order (orders table) based on the
locale relationship stored in the orders table using a pivot table (order_status_locale table).
The pivot table contains the "localised" order status from the order.
Of course, I could fetch the localised order status (order_status_locale) directly from the database, but I'd like to
fetch the localised order status through a Laravel relationship.
Something like this:
$order = Order::find(123);
$order->localisedOrderStatus->label;
This is an example of the database structure:
orders:
id: int
locale_id: int
...other columns
locales:
id: int
...other columns
order_statuses:
id: int
...other columns
order_status_locale:
order_status_id: int
locale_id: int
label: varchar
its sometimes better to make model of your pivot table. like OrderStatusLocale.php
then you can make the relation through it.
lastly if you want to achieve
$order->localisedOrderStatus->label;
you can use laravel has one through. or i think its better to go through the relation like $order->order_status->locale->label

Build tree of database schema in PHP

I have some files with names of tables and names of tables which are referenced by the current table like this:
table1
table2, table3
-
table 2
table 4
This means table1 references to tables table2 and table3, and table2 references to table4.
How can I to build the tree of tables, where keys are "parent" tables and children are referenced tables like this:
[table4] => array(
[table2] => array([table1] => null),
)
[table3] => array([table1] => null)
So, my problem is I know how to parse to tree records in file like this:
name | parent
------------------
table 1 | table 2
table 2 | table 4
But I don't know the best way how to parse to tree the structure, when ONE node has MULTIPLE parents.
Correct me if I'm wrong but that's not enough to have just the table you need also a table design. Hence you need a field value and a field id. That field id is most likely an unique id and can reference to the same table or to another table. For example table 1 has a field title and a field id. If the id reference to the same table you can use a self join. This model is called adjacency list model but I'm not sure what's the direction of the reference.

SQL return only not empty columns from row as new row

I'm in the situation where my client e-mails me an excel-file with 50 columns of data extremely un-normalized. I then export it to CSV and upload into MySQL -- single table. The columns are for different ingredients (10 columns of data for each ingredient -- title, category, etc) and then 40 different columns for characteristics on each ingredients. So each ingredient in the table has all of these 50 columns even though every column doesn't apply for that ingredient.
My question is if I can create a SQL that selects only filled in characteristics for one selected ingredient and leaves out all of the other columns?
(I know that another option is to build my own CSV-parser that created multiple tables and then write SQL for them instead, but I wanna investigate solving this as is first. If that's not possible then I just have to face that and build a parser ;P)
This is as far as I came but this doesn't completely exclude columns not filled in (or that contains "nei".
SELECT
IF(`Heving-vanlig-gjaerbakst` <> '' AND `Heving-vanlig-gjaerbakst` <> 'nei', `Heving-vanlig-gjaerbakst`, 'random') AS `test1`,
IF(`Frys-kort` <> '' AND `Frys-kort` <> 'nei', `Frys-kort`, 'random') AS `test2`
... and for the 38 other rows ...
FROM x
WHERE id = 123
And I'd rather not solve this in the PHP-code by skipping empty rows =P
Example row (column names first):
g1 gruppe ug1 undergruppe artnr artikkel beskrivelse status enhet ansvar prisliste Heving-vanlig-gjaerbakst Heving-soete-deiger Deig-stabilitet Smaksgiver Saftighet Krumme-poring Skorpe Volum Konservering Skjaerbarhet Frys-lang Frys-kort Kjoel Holdbarhet E-fri Azo-fri Mandler Aprikoskjerner Helmiks Halvmiks Base Konsentrat Utstrykning Bakefasthet Frukt-Baerinnhold Slippegenskaper Hindre-koksing Palmefri Fritering Smidighet Baking Kreming Roere Fylning Dekor Prefert Viskositet Cacaoinnhold Fet-innhold
100150 Bakehjelpemidler 100150200 Fiber/potetprodukter 10085 Potetflakes sekk 15 kg Egnet til lomper, lefser, brød og annet bakverk. B... Handel Sekk Trond Olsen JA xxx xxx xxx
As you can see most columns are empty here. X, XX and XXX is a form of grade-system, but for some columns the content is instead "yes" or "no".
And as I said, the first 10 columns are information about that product, the other 40 is different characteristics (and it's those I wanna work with for one given product).
It sounds a bit as if you'd like to convert the table you have into two tables:
CREATE TABLE Ingredients
(
g1 ...,
gruppe ...,
ug1 ...,
undergruppe ...,
artnr ... PRIMARY KEY,
artikkel ...,
beskrivelse ...,
status ...,
enhet ...,
ansvar ...,
prisliste ...
);
I've opted to guess that the artnr is the primary key, but adapt what follows to the actual primary key. This table contains the eleven (though your question said ten) columns that are common to all ingredients. You then have another table which contains:
CREATE TABLE IngredientProperties
(
artnr ... NOT NULL REFERENCES Ingredients,
property VARCHAR(32) NOT NULL,
value VARCHAR(3) NOT NULL,
PRIMARY KEY(artnr, property)
);
You can then load the populated columns from your original table into these two. At worst, there'd be 40 entries in IngredientProperties for one entry in Ingredient. You might make 'property' into a foreign key reference to a defining list of possible ingredient properties (a third table that defines the possible values for the properties - basically, a record of the column names from your original table). If you add the third table, it might logically be called IngredientProperties (too), in which case the table I called IngredientProperties needs to be renamed.
You can then join Ingredients and IngredientProperties to get the information you want.
I'm not sure that I recommend this solution; it is basically a use of the 'Entity Attribute Value' approach to database design. However, for extremely sparse information like you seem to have, and when used with the constraint of the third table.
What you can't sensibly do is handle all possible combinations of 40 columns as that number grows exponentially with the number of columns (and is pretty large with N = 40).

Finding value in a comma-separated text field in MySQL?

I've got a database of games with a genre field that has unique ids in it that are separated by commas. It's a text field. For example: HALO 2 - cat_genre => '1,2' (Action,Sci-Fi)
I'm trying to make a function that calculates the total number of games in that genre. So it's matching 1 value to multiple values separated by commas in the db.
I was using SELECT * FROM gh_game WHERE cat_genre IN (1) which would find Action Games.
I'm trying to work this out, I thought I had nailed it once before but I just can't figure it out.
You need to create a many to many relation. like so
CREATE TABLE gameGenreTable ( id int NOT NULL PRIMARY KEY, genreID, gameID)
EDIT: if you're using InnoDB you can also create foreign keys on genreID and gameID..
I would add a UNIQUE key on genreID, gameID
then you can do a query like this
SELECT genreID,count(genreID) as count from gameGenreTable GROUP BY genreID;
-- and join in your other table to get the genre name (or just use the ID).

A large amount of foreign keys in mysql ? this is good?

Hey guys (and probably girls). I'm modelling a huge database in mysql for a company that i work and i'm stucked on things that you might help me.
My question is very simple: How do i know that a number of foreign keys is enought ?
I have 8 tables that describes the following datas:
1st relationship
table country (pais)
table state (estado)
table city (cidade)
(city => state => country)
2nd relationship
table department (departamento)
table sector (setor)
table role (cargo)
(role => sector => department)
3rd relationship
legal entity (entidade juridica)
company (empresa)
(company => legal entity)
And finally i have a ninth table called employee and this table have foreign key references of all the tables previously described.
(primary) id-colab
fone_colaborador
fax_colaborador
ativo_colaborador
email_colaborador
(primary) cargo_id_cargo (cargo table)
(primary) cargo_setor_id_setor ( cargo table)
(primary) cargo_segor_departamento_id_departamento (cargo table)
(primary) empresa_id_empresa (empresa table)
(primary) empresa_entidade_juridica_id_entidade_juridica (empresa table)
(primary) empresa_entidade_juridica_cidade_cidade_id (empresa table)
(fK) cargo table
(fk) empresa table
The main concept of this model is.
I have a register of a legal entity.
legal entity must be placed on country => state => city
I have a register of a company
Company should inform whether it is a branch or parent company
Company should have a referece to the legal entity table (that owns address, phone, state id, city id, country id, postal code and etc...)
I have a register of a role
Role should have a reference to the sector table
sector table should have a reference to the department table
And finally, the main table called employee described on the image above.
I hope you guys have undertood me !
See ya.
You can have 100 foreign keys in your table if that's what's required to keep your data properly normalized. Don't worry about the number. Worry about keeping your fields appropriately atomic and your schema normalized.

Categories