除非我遗漏了什么,否则这听起来像是一个典型的JOIN 查询。
假设您有两个表,如下所示:
CREATE TABLE Threads (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
originalAuthorId INTEGER,
subject VARCHAR(100),
created DATETIME,
deleted INTEGER );
CREATE TABLE Posts (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
threadId INTEGER,
authorId INTEGER,
body TEXT,
created DATETIME,
deleted INTEGER,
FOREIGN KEY (threadId) REFERENCES Threads (id)
ON DELETE CASCADE
ON UPDATE CASCADE );
您一次选择所有内容的查询将如下所示:
SELECT
t.id AS "threadId",
t.originalAuthorId,
t.subject AS "threadSubject",
t.created AS "threadCreated",
p.id AS "postId",
p.authorId,
p.body,
p.created AS "postCreated"
FROM
Threads t JOIN Posts p
ON t.id = p.threadId
WHERE
t.deleted = 0 AND
p.deleted = 0;
该查询将生成一个包含八列的表:threadId、originalAuthorId、threadSubject、threadCreated、postId、authorId、body 和 postCreated。
如果这不是您要查找的内容,请发表评论或更新您的原始问题,我会尽力提供帮助。
编辑:
根据下面的评论,您可以通过以下方式优化大量数据的查询。我将使用 PHP 作为示例脚本语言。
// Set $dbh to a PDO object pointing to your database.
$sql = "SELECT id, originalAuthorId, subject, created FROM Threads ".
"WHERE deleted = 0";
$sth = $dbh->query($sql);
$threads = array( );
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
$threads[$row['id']] = $row;
$sql = "SELECT id, threadId, authorId, body, created FROM Posts ".
"WHERE deleted = 0 ORDER BY threadId";
$sth = $dbh->query($sql);
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
$posts[$row['id']] = $row;
// At this point, you can view your post information, sort it using whatever
// sort mechanism you want, etc. You can get access to the thread information
// in the thread array. For example:
foreach ($posts as $k => $v)
echo "Post ".$k." created at ".$v['created']." belongs to thread ".
$v['threadId']." by author id ".
$threads[$v['threadId']]['originalAuthorId']. " created ".
$threads[$v['threadId']]['created']."\n";
如果您有大量数据,您可以通过同时向数据库打开两个语句句柄并通过巧妙的排序同时迭代它们来获得真正的幻想。这是一个更复杂的例子:
// Set $dbh to a PDO object pointing to your database.
$sql = "SELECT id, originalAuthorId, subject, created FROM Threads ".
"WHERE deleted = 0 ORDER BY id";
$sthThreads = $dbh->query($sql);
$sql = "SELECT id, threadId, authorId, body, created FROM Posts ".
"WHERE deleted = 0 ORDER BY threadId";
$sthPosts = $dbh->query($sql);
$rowThread = null;
while ($rowPost = $sthPosts->fetch(PDO::FETCH_ASSOC)) {
// You REALLY want a foreign key constraint for the following statement!
while ($rowThread === null || $rowThread['id'] !== $rowPost['threadId'])
$rowThread = $sthThreads->fetch(PDO::FETCH_ASSOC);
echo "Post ".$rowPost['id']." created at ".$rowPost['created'].
" belongs to thread ".
$rowPost['threadId']." by author id ".
$rowThread['originalAuthorId']. " created ".
$rowThread['created']."\n";
}
(请记住,我只是在袖手旁观,所以提前为任何语法错误或语法道歉。)