How do I relate multiple rows in two tables? - sql

I have two tables:
table1:
id(int) | stuff(text)
-------------------------
1 | foobarfoobarfoo
2 | blahfooblah
3 | foo
table2:
id(int) | otherstuff(text)
--------------------------
1 | foo
2 | bar
3 | blah
A row in table1 can have more than one of foo, bar etc. And, each row in table2 can appear in more than one row of table1.
Which is a better way of keeping this straight. Should I create a third table like this:
table3:
id_from2(int) | id_from1(int)
-----------------------------
1 | 1
1 | 2
1 | 3
2 | 1
3 | 2
Or, should I have an column of type array added to table1 and table2 to keep track of the same information?

Yes, using junction tables is the correct way of implementing many-to-many relations in RDBMS.
You can add more attributes to your junction table (i.e. table3) if necessary. For example, if the relations are ordered, you can add a third field that specifies an ordering of the (table1, table2) combinations. Here is a link to an answer on Stack Overflow that gives a nice detailed example of a many-to-many table.

This is a standard Many-To-Many design, most flexible solution would be a third table with id associations as you shown.

Can't agree more. Your design of adding a third table is correct.

Relation table is the best way to relate many-to-many relationships. You did it well.

So you want a many to many relationship? One from table 1 can have relation to more objects in 2, and the other way around? Yes, use a third table like you said, it's a best practice. Also attach a primary key autoincrement column, just to be safe

Related

Postgresql - Composite Key and two tables, or just 1 wide table?

I am constructing a horse racing database, but I am struggling figuring out the best possible design.
Option 1)
2 Tables, 1 for "race", the other for "horses"
This would look like this
Table 1: ID | Date | Time | Race Name | Weekday | Course | Distance | Going | Class | Pricemoney | Number of Starters | Finishing time | Type Of Race
Table 2:
Race ID | Finishing Number 1 | Horse Name| Jockey | Trainer | Weight | Age | Sectional Speed | and so on
Race ID | Finishung Number 2 | .....
Question to this Design: How do I define a Composite Primary Key on Date, Time, Course and Racename and links this as a foreign key to Race ID in Table 2? I use Postgresql (via. pgadmin4)
Option 2:
One wide table, with the race data, and then the horses following on one row (finishing number 1 | 2 | 3 .... until up to 30 on very rare occasions)
Problem with this design is that not every race has the same number of starters, so there would be a lot of null entries in the rows from horse number 8 to 30.
Advantage would be, that i would not have to join the tables for queries, Most queries would require a complete join, as nearly all the data in this table is required on every query.
The table would consist of roughly 360-400 columns (wide) and up to 20.000 (maybe more) rows.
Question: Would this be problem performance wise? I would make only a few queries a day
Thanks a lot
A wide table is the datawarehouse approach. This may be appropriate when dealing with billions of rows. But datawarehouses often get their data from pure relational databases, so it is ensured that data is consistent.
Joins are something an RDBMS is made for. They are usually fast. Don't worry about this. my advice is: Build a proper normalized database.
There are races and horses. In one race there are multiple horses and one horse can participate in multiple races. That is an m:n relation for which you need a bridge table.
The tables:
horse (horse_id, horse_name, birth_date, trainer, ...)
race (race_id, date_time, race_name, course, distance, price_money, ...)
participation (horse_id, race_id, jockey, weight, position, ...)

Which query in database is better?

suppose to I have one table and filter by type like wordpress database
// general table
id | title | content | type
---------------------------
1 | hello | some... | post
---------------------------
2 | image | con | image
select * post where type = post
or
// table post
id | title | content
--------------------
1 | hello | some...
select * post
//table image
id | title | content
---------------------
2 | image | con
select * image
so I mean that if I make more table is better or make a single table for my database?
The idea in database design is to have one table per "entity" -- hence the name, "entity-relationship modeling".
It seems reasonable to think that "images" and "posts" are quite different things and should go into their own tables.
That does not mean that "more tables are better". It means that "the appropriate tables are best". In particular, it is generally a bad idea to split an entity across multiple tables.
It is always better to have table per business entity. Business keeps on changing in future, and thus it becomes hard to maintain data in single table. So Posts and Image should be 2 tables. No second thoughts.
the multi table in large project and for small project the general table is better

Normalization of multiple similar tables

i'm quite new to all this tech stuff so excuse me for making mistakes - beforehand.
My question is regarding data normalization. I'm using PGadmin4 for this task.
I have multiple tables one for each year containing multiple columns. I wish to normalize these data in order to make further inquiries. The data is in this form:
Table 1
| id | name1 | code1| code2 | year|
| 1 | Peter | 111 | 222 | 2007|
Table 2
| id | name1 | code1| code2 | year|
| 2 | Peter | 111 | 223 | 2008|
So my tables area similar but with some different data each year
I have broken it down so i have multiple tables containing only one column of information:
name1_table
| id | name1 |
And i have done this by every column. Now i need to link it all together - am heading in the right direction or have i gone of in a bad one?
What is the next step and if possible what is the code i need to use.
The easiest way to combine two tables with identical schemas is to create a new third table with the same schema and copy all the records into it.
Something like this:
INSERT INTO Table3 SELECT * FROM Table1;
INSERT INTO Table3 SELECT * FROM Table2;
Or if you simply need a combined query result you can use UNION:
SELECT * FROM Table1
UNION
SELECT * FROM Table2;
You are not headed in the right direction. The best approach is simply to store all the data in one table and to use indexes and/or partitions to access particular rows.
Sometimes this is not possible, notably because the tables have different formats. Possible solutions:
Break the existing tables into similarity sets based on columns, and create one table for each similarity set.
Create a table based on the most recent definition of the table, NULLing out columns that don't exist in historical tables.
Use a facility such as JSON for columns that have changed over time.
Use a facility such as inheritance for columns that have changed over time.

SQL Server 2012 Query to extract subsets of data

I'm trying to 2nf some data:
Refid | Reason
------|---------
1 | Admission
1 | Advice and Support
1 | Behaviour
As you can see one person might have multiple reasons so i need another table to have the following format:
Refid | Reason1 | Reason2 | Reason3 | ETC...
------|-----------|--------------------|-----------
1 | Admission | Advice and Support | Behaviour
But I don't know how to write a query to extract the data and write it in a new table like this. The reasons don't have dates of other criteria that would make any reason to be in any special order. All reasons are assigned at the time of referral.
Thanks For yor Help.. SQL Server 2012
You are modelling a many to many relationship
You need 3 tables
- One for Reasons (say ReasonID and Reason)
- One for each entity identified by RefID (say RefID and ReferenceOtherData)
- An junction (or intersection) table with the keys (RefID, ReasonID)
This way,
Multiple reasons can apply to one Ref entity
Multiple Refs can have the same reason
You turn repeated columns into rows.

SQL : ER Model, Foreign keys

I have a simple question, but I am still confused about it.
Whenever you design an ER model, how are you supposed to draw PK's and FK's ?
Let's say I have two tables, User and Country
User
ID | firstName | lastName | FKCountry
1 | John | Stewart | 1
2 | Paul | Duschmol | 2
etc.
Country
ID | country | code
1 | Germany | GER
2 | Switzerland | CH
etc...
Well, should I add the column "FKCountry" in the ER model or not ? I mean, there will be the relation (Rhombus) between both entities, but should I explicitly add the "FKCountry" by the User entity ?
Hope my question is clear, Thank you in advance :)
The primary purpose of Foreign Key is to enforce referential integrity between the two tables.
If the relationship of Country to a User is One-to-Many then it should be fine for adding column FKCountry on table User.
However, if the relationship is Many-to-Many in which Country can have many User as well as User belongs to multiple Country, then a 3-table design is much preferred. Wherein the 3rd table is the association table between the other two.
Yes, you should add FKCountry to the User table in your ER diagram. If the column exists in your table, it should be represented in the entity. There should be zero doubt that the relational marker connects Country.ID to User.FKCountry. Just because it is obvious in this example does not mean that in other relationships, the linked columns might not be named completely differently and not obvious.