优化 MySQL 查询所需的建议
我正在使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 where 子句中使用 join 而不是匹配列
And
use join instead of matching columns in where clause
And
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.