SQLite field with a list of foreign keys

心不动则不痛 提交于 2019-12-08 09:32:54

问题


I am building an SQLite DB to keep my real estate agents' listings. I have been able to use a foreign key to identify a listing for each agent, but I want to make a list of listings in each agent's record; moving from a one-to-one relationship between agents and listings to a one-to-many relationship.

Looking here: http://www.sqlite.org/draft/foreignkeys.html , there is no mention of a field that is a 'list of foreign keys'. Is what I'm trying doable?

I considered that, as a workaround, I might make a table that contains the relationships themselves, but that doesn't seem to be a very clean solution. I looked at this thread: SQLite foreign key examples , but I'm not sure that my elements are similar to the many-to-many relationship they describe there.

I am also open to suggestions on how this can be done better. Should I just include a listing agent's name on the actual listing table and just query from there?

CREATE TABLE listings
(
    listing_id        INTEGER PRIMARY KEY AUTOINCREMENT,
    listing_address   TEXT UNIQUE NOT NULL,
    acq_date          DATE
 )

CREATE TABLE agent
(
     agent_id         INTEGER PRIMARY KEY AUTOINCREMENT,
     agent_name       TEXT NOT NULL,
     agent_listings   INTEGER,
     FOREIGN KEY (agent_listings) REFERENCES listings (listing_id) NOT NULL
 )

回答1:


You need to add the foreign key to the listings table instead; for a one-to-many relationship it is the 'many' side that records the foreign key.

CREATE TABLE listings
(
    listing_id        INTEGER PRIMARY KEY AUTOINCREMENT,
    listing_address   TEXT UNIQUE NOT NULL,
    acq_date          DATE
    agent_id          INTEGER,
    FOREIGN KEY (agent_id) REFERENCES agent (agent_id)
)

CREATE TABLE agent
(
     agent_id         INTEGER PRIMARY KEY AUTOINCREMENT,
     agent_name       TEXT NOT NULL,
)

If you wanted listings to be handled by multiple agents (in a many-to-many relationship), you'll have to add a linking table:

CREATE TABLE listings
(
    listing_id        INTEGER PRIMARY KEY AUTOINCREMENT,
    listing_address   TEXT UNIQUE NOT NULL,
    acq_date          DATE
)

CREATE TABLE agent
(
    agent_id          INTEGER PRIMARY KEY AUTOINCREMENT,
    agent_name        TEXT NOT NULL,
)

CREATE TABLE agent_listings
(
    agent_id         INTEGER NOT NULL,
    listing_id       INTEGER NOT NULL,
    UNIQUE (agent_id, listing_id),
    FOREIGN KEY (agent_id) REFERENCES agent (agent_id),
    FOREIGN KEY (listing_id) REFERENCES listings (listing_id),
)


来源:https://stackoverflow.com/questions/20572158/sqlite-field-with-a-list-of-foreign-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!