php – Suggestion needed for optimizing a MySQL query – Education Career Blog

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


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?


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


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.

Leave a Comment