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:
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?
答案 0 :(得分:1)
You could do that in SQL.
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.