我需要在Android应用程序中创建一个非常简单的数据库(我正在使用SQLite)并且不知道如何进行此查询。
假设我有这两个表,与第一个locationid
链接在一起:
CREATE TABLE locations
(
locationid INTEGER PRIMARY KEY AUTO_INCREMENT,
floor INTEGER,
room INTEGER
);
CREATE TABLE entries
(
entryid INTEGER PRIMARY KEY AUTO_INCREMENT,
title TEXT,
summary TEXT,
date DATE,
FOREIGN KEY(location) REFERENCES locations(locationid)
);
如何构建以下查询:获取房间308,3楼的表“条目”中的所有行?
答案 0 :(得分:1)
SELECT *
FROM entries
WHERE locations = (SELECT locationid
FROM locations
WHERE room=308
AND floor=3)
可替换地:
SELECT e.*
FROM entries e
JOIN locations l ON e.locations = l.locationid
WHERE l.room = 308
AND l.floor = 3
答案 1 :(得分:0)
SELECT e.*
FROM locations l INNER JOIN entries e
ON l.locationid = e.location
WHERE l.floor = 3
AND l.room = 308
答案 2 :(得分:0)
这是一个简单的JOIN声明:
select
locations.*, -- suppress this if only entries table are needed
entries.* -- you can select only date and title instead of everything
from locations
join entries
on entries.location=locations.locationid -- using your foreign key
where
locations.room=308 -- first condition
and locations.floor=3 -- second condition
;
如果要在房间中检索信息(例如),即使条目表中没有数据链接,也可以使用LEFT JOIN而不是JOIN。
最后一句话:我非常确定答案已经在stackoverflow和网络上了。