优化 MySQL 查询所需的建议

发布于 2024-09-28 10:15:10 字数 519 浏览 8 评论 0原文

我正在使用 PHP 参数化查询,我有以下两个查询:

SELECT username,question_text 
FROM questions,users 
WHERE questions.question_id = 4 AND questions.user_id = users.user_id

简而言之

SELECT username, post_text 
FROM posts,users WHERE posts.question_id = 4 
AND posts.user_id = users.user_id ORDER BY posts.post_id ASC

,这些问题正在“posts”表中讨论,并由其 Question_id 引用。

我的 PHP 代码中有一些冗余代码,因为我不知道足够的 mysql 来查询数据库一次以从这两个查询中获取我需要的结果。

我处理 PHP 代码的冗余部分的方式是否正确,或者是否有更好的方法来实现这一点?

I'm using parameterized queries with PHP I have the following two queries:

SELECT username,question_text 
FROM questions,users 
WHERE questions.question_id = 4 AND questions.user_id = users.user_id

and

SELECT username, post_text 
FROM posts,users WHERE posts.question_id = 4 
AND posts.user_id = users.user_id ORDER BY posts.post_id ASC

In short, the questions are being discussed in the "posts" table and are being referenced by their question_id.

I have some redundant code in my PHP code because I don't know enough mysql to query the database once to get the results I need out of these two queries.

Is the way I'm doing it fine and deal with the redundant parts of my PHP code or is there a better way of accomplishing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

面犯桃花 2024-10-05 10:15:10

在 where 子句中使用 join 而不是匹配列

SELECT username,question_text 
FROM questions INNER JOIN users on questions.user_id = users.user_id
WHERE questions.question_id = 4

And

SELECT username, post_text 
FROM posts INNER JOIN users on posts.user_id = users.user_id 
WHERE posts.question_id = 4 
ORDER BY posts.post_id ASC

use join instead of matching columns in where clause

SELECT username,question_text 
FROM questions INNER JOIN users on questions.user_id = users.user_id
WHERE questions.question_id = 4

And

SELECT username, post_text 
FROM posts INNER JOIN users on posts.user_id = users.user_id 
WHERE posts.question_id = 4 
ORDER BY posts.post_id ASC
风向决定发型 2024-10-05 10:15:10

2 个查询完全没问题,合并多个表的输出并不是一个很干净的想法。

你只需要检查你在 WHERE 中使用的所有字段是否有所有组合索引,这会非常快。

2 queries is totally fine there, combining output from several tables is not very clean idea.

You just need to check if you have all combined indexes on all fields you use in WHERE, and it will be very fast.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文