你可以使用 SQL 子选择(如果我理解你的问题)。使用 PHP 会很奇怪,而 SQL 却拥有所有功能。
SELECT *
FROM `post`
WHERE `id` IN (
SELECT `post_id`
FROM `tag_post`
WHERE `tag_id` = (
SELECT `tag_id`
FROM `tag`
WHERE `tag` = 'mysql'
)
)
我不确定你的数据库结构是什么样的,但这应该可以帮助你开始。这几乎是 SQL 的开始。查询中的查询。您可以使用子选择的结果来选择数据。
请在复制此 SQL 并告诉我它不起作用之前,验证所有表和列名称。
在有人开始抱怨速度、缓存和效率之前:我认为这相当高效。您可以使用本机 SQL 选择较小的位,而不是使用 PHP 选择所有数据并循环遍历它。
再次强调,我强烈反对使用 PHP 来获取特定数据。 SQL 就是您所需要的。
编辑:这是你的脚本
假设您有一些包含所有数据的多维数组:
// dummy results
// table tag
$tags = array(
// first record
array(
'id' => 0,
'tag' => 'mysql'
),
// second record
array(
'id' => 1,
'tag' => 'php'
)
// etc
);
// table tag_post
$tag_posts = array(
// first record
array(
'id' => 0,
'post_id' => 0, // post #1
'tag_id' => 0 // has tag mysql
),
// second record
array(
'id' => 1,
'post_id' => 1, // post #2
'tag_id' => 0 // has tag mysql
),
// second record
array(
'id' => 2,
'post_id' => 2, // post #3
'tag_id' => 1 // has tag mysql
)
// etc
);
// table post
$posts = array(
// first record
array(
'id' => 0,
'content' => 'content post #1'
),
// second record
array(
'id' => 1,
'content' => 'content post #2'
),
// third record
array(
'id' => 2,
'content' => 'content post #3'
)
// etc
);
// searching for tag
$tag = 'mysql';
$tagid = -1;
$postids = array();
$results = array();
// first get the id of this tag
foreach($tags as $key => $value) {
if($value['tag'] === $tag) {
// set the id of the tag
$tagid = $value['id'];
// theres only one possible id, so we break the loop
break;
}
}
// get post ids using the tag id
if($tagid > -1) { // verify if a tag id was found
foreach($tag_posts as $key => $value) {
if($value['tag_id'] === $tagid) {
// add post id to post ids
$postids[] = $value['post_id'];
}
}
}
// finally get post content
if(count($postids) > 0) { //verify if some posts were found
foreach($posts as $key => $value) {
// check if the id of the post can be found in the posts ids we have found
if(in_array($value['id'], $postids)) {
// add all data of the post to result
$results[] = $value;
}
}
}
如果您查看上面脚本的长度,就会发现这正是我坚持使用 SQL 的原因。
现在,我记得,你想要join
使用 PHP,而不是使用 SQL。这不是连接,而是使用一些数组获取结果。我知道,但加入只会浪费时间,而且比保留所有结果的效率更低。
编辑:21-12-12 作为以下评论的结果
我做了一些基准测试,结果非常惊人:
DATABASE RECORDS:
tags: 10
posts: 1000
tag_posts: 1000 (every post has 1 random tag)
Selecting all posts with a specific tag resulted in 82 records.
SUBSELECT RESULTS:
run time: 0.772885084152
bytes downloaded from database: 3417
PHP RESULTS:
run time: 0.086599111557
bytes downloaded from database: 48644
Please note that the benchmark had both the application as the database on the
same host. If you use different hosts for the application and the database layer,
the PHP result could end up taking longer because naturally sending data between
two hosts will take much more time then when they're on the same host.
尽管子选择返回的数据少得多,但请求的持续时间却长了近 10 倍......
我从来没有预料到这些结果,所以我确信,当我知道性能很重要时,我肯定会使用这些信息,但我仍然会使用 SQL 进行较小的操作,呵呵...