问题
As in this question (SQLite field with a list of foreign keys), I'm trying to keep my real estate agents and listings in an SQLite DB with python.
I did as suggested and now have tables that look like this:
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,
agent_last_request TEXT
)
I am now trying to update the agent table based on calculations done from the listing. My theory is that there must be a one-line-of-sql way to update a field using the foreign key from another table's row. I already have this working, in fact:
given my_listing_id
given new_request_data
"SELECT agent_id FROM listings WHERE listing_id = ?", (my_listing_id,)
fetch etc..
"UPDATE agent SET agent_last_request = ? WHERE agent_id = ?", (new_request_data, agent_id)
But in the interest of doing this right, it seems to me that there should be one line of SQL that uses the foreign key to update another table. I tried stuff like this, but failed:
"UPDATE agent, listings SET agent_last_request = ? WHERE agent.agent_id = listings.agent_id AND listings.agent_id = ?", (new_request_data, my_listing_id)
So how do I update agent_last_request when I have my_listing_id? Should I keep doing it the long way?
回答1:
To look up a single value, you can use a scalar subquery:
UPDATE agent
SET agent_last_request = ?
WHERE agent_id = (SELECT agent_id
FROM listings
WHERE listing_id = ?)
来源:https://stackoverflow.com/questions/20662547/sqlite-update-field-in-one-table-based-on-foreign-key-of-another-table