转换为加入
我有一个效率相当低的查询,我认为我可以使用 SQL JOIN 来减少它。
这是两个查询:
$data = $db->query("SELECT * from tbl_forums_threads WHERE tid = '$id'");
$threaddata = $data->fetch_assoc();
$dataset = $db->query("SELECT * from tbl_forums_posts WHERE tid = '$id'");
$thread = $dataset->fetch_assoc();
显然,它们有 1 个共同点:使用 $id。
我可以使用 SQL JOIN 甚至 LEFT JOIN 吗?
谢谢!
I've got a query that's rather inefficient, and I think that I can use SQL JOIN to cut it down.
Here are the two queries:
$data = $db->query("SELECT * from tbl_forums_threads WHERE tid = '$id'");
$threaddata = $data->fetch_assoc();
$dataset = $db->query("SELECT * from tbl_forums_posts WHERE tid = '$id'");
$thread = $dataset->fetch_assoc();
Obviously, they have 1 thing in common: the use of $id.
Could I use SQL JOIN, or even LEFT JOIN?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过在每个表的
tid
列上创建索引,您可以获得比更改查询更好的改进。使用基本 where 子句对单个表进行简单的
select
应该不会很慢;如果是,可能是因为他们没有使用索引。在这种情况下,您只过滤一个字段,因此这是需要索引的唯一可能性。You'd get far better improvements by creating indices on the
tid
column in each table than you would by changing the queries.Simple
select
s on a single table with a basic where clause should not be slow; if they are, it's probably because they're not using an index. In this case, you're only filtering on one field, so that's the only possibility for needing an index.1 个带有 JOIN 的 SQL 查询不一定比 2 个这样的简单查询更快。
在我看来,留下来吧。
1 SQL query with a JOIN isn't necessarily faster than a 2 simple query like that.
Stay with this imo.