简体   繁体   中英

SQL, piece of data knows what table it comes from

Let's say I have 4 tables containing data of different categories:

Audiobooks
Music
Text 
Films

Each table contains relevant to the category data, ie

Films would contain .mp4 files and Music will contain .mp3 and so on.

An extra table exists called Content , which has all the data from all other 4 tables and contains columns with extra information about the files.

If I extract a row from the Content's table, I want to know where that file originated from (what table it comes from), WITHOUT having to search through ALL the tables and see which one contains that filename or UUID (coz filenames may clash), and without having to put an extra column in the Contents table saying the tablename of that file.

I searched Google and StackOverflow for similar qns but none gave a desired answer yet. Maybe I'm asking for too much.

I don't like your Database design. This could be solved with a better design without duplicate information in different places.

Having said that: you could make an extra table with all the ids from your Content table and a reference to what table: Audiobooks, Music, Text or Films and what id in that table the record refers to.

Why do you need the information in all those tables, why isn't the Content Table enough?

Without changing your database design:

You could change the strategy you store your UUID's, so the every text will begin with "TXT" and "Film with "MP4", etc. That way, some simple logic on your database access object wrapper like

If (UUID.substring(0,3) = "MP4") sqlQuery = SELECT * FROM Films WHERE UUID = SqlUUID
If (UUID.substring(0,3) = "TXT") sqlQuery = SELECT * FROM Text WHERE UUID = SqlUUID

etc.

If you're not using a DAO wrapper then you'll have to write the string on SQL...and that is very messy. On the other hand, if you have something on the Contents table that distinguishes between the different files, for example a file extension column, you could just make 2 queries, the first one to find out which table you should be querying.

Overall though, Pieter is right; you should change your database design.

I don't see why you couldn't have merged the Content table with the other tables. If the length of output is a problem, just select the relevant columns instead of everything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM