开发者

Suggestion needed for optimizing a MySQL query

开发者 https://www.devze.com 2023-01-20 19:03 出处:网络
I\'m using parameterized queries with PHP I have the following two queries: SELECT username,question_text

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, pos开发者_如何学Got_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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消