SQL: Add A Foreign Key relation to two existing(filled) tables

时间:2015-05-12 22:12:40

标签: mysql foreign-keys foreign-key-relationship

I have two tables: One table is the <script> table that contains the album name, author and genre(s) (As well as an insertion timestamp). The other is the albums table, which contains information about each of the tracks on an album (As well as an insertion timestamp).

Today I realized that a lot of data in my tables is double: In the tracks table, I also store the album and author name, while it would be nicer to select them from the other table by referencing them only with an ID.

I know I can uniquely identify the album each track belongs to because it has:

  • The same album name
  • A timestamp which is not more than a few seconds apart.

Is there a way for me to create a column that references the album_id from SQL alone, or do I need to write a program in e.g. PHP to accomplish this?

2 个答案:

答案 0 :(得分:1)

You could do that in SQL.

  • Add album id to tracks table (would have to be nullable to begin with)
  • Add foreign key
  • Update tracks table based on some common property such as album name
  • Make foreign key not nullable, optional step

e.g.

hidden

答案 1 :(得分:0)

If you haven't already added the album_ID column I'd suggest the following commands:

To add album_ID:

        engine = create_engine('mssql+pymssql://xx:xxx@xxx/xxx', implicit_returning=False)
        metadata = MetaData()
        tables = ['xxx', 'xxx', 'xxx']
        metadata.reflect(engine, only=tables)
        base = automap_base(metadata=metadata)
        base.prepare()
        session_maker = sessionmaker(bind=engine)
        session = session_maker()

To add the foreign key:

ALTER TABLE albums ADD album_ID VARCHAR(10);
ALTER TABLE tracks ADD album_ID VARCHAR(10);

To drop album name and author name:

ALTER TABLE tracks ADD FOREIGN KEY (album_ID) REFERENCES albums(album_ID);

Then populate the album ID's in both tables.