r/DatabaseHelp • • May 13 '15

Database Structure Help

Hi,

I'm setting up a database that will store information on Reports I will be making. These reports will take data inputs from a variety of Data sources depending on what the user wants.

So I have a table with my Data Sources set up like this:

sourceIDsourceNamesourceURL
1JohnJohn.com
2PetePete.com
3ChrisChris.com
4DaveDave.com
5JamesJames.com

Now I want to set up a 'Reports' table which identifies which sources the report needs. I have the following set up:

reportIDreportNamesources
1Engineers1,2,4
2Builders3,5

I also thought of doing it like the below - however there will be lots of sources so I don't want to add a new column to the reports table every time I add a new data source:

reportIDreportNamesource1source2source3source4source5
1Engineers11010
2Builders00101

There must be a better way to structure my tables! Any ideas?

1 Upvotes

3 comments sorted by

3

u/[deleted] May 13 '15

You need a report_sources (junction) table.

Remove the sources field from Reports and make sourceId and reportID the Primary Keys in this new table.

1

u/[deleted] May 13 '15

Thank you very much. This looks great

1

u/wolf2600 May 13 '15 edited May 13 '15

In your Reports table, you have multiple values being stored in a single field (ie: "1,2,4"). That's not allowed; each field can only contain a single value.

Need to have something like

ReportSources
--------------------------------------
reportSourceID    reportID sourceID
    1               1      1
    2               1      2
    3               1      4
    4               2      3
    5               2      5

Reports
----------------------------------------
reportID     reportName
    1             Engineers
    2             Builders

Then do a query like

select sourceName from dataSources where sourceID in
    (select sourceID from ReportSources
     inner join Reports
     on ReportSources.reportID = Reports.reportID
     where Reports.reportName = 'Builders') ;

To get a list of all the builders sources.