I wanted to see if I can better organize / optimize my code, and so I’ve been reading more about joins and how you can query / select from two different tables where a certain column matches up in a single query. However, I could not find any documentation on what I would like to do.
Consider two tables (A , B).
Table A user_id -- + -- course_id 1 -- + -- 1 Table B course_id -- + -- project_id 1 -- + -- 2
My queries look something along the lines of the following:
$sql_course= mysql_query("SELECT course_id FROM A WHERE user_id = 1") or die(mysql_error());
while ($course_row = mysql_fetch_assoc($sql_course)) {
// Unique course ID
$courseID = $course_row['course_id'];
$sql_b= mysql_query("SELECT project_id FROM B WHERE course_id=$courseID") or die(mysql_error());
So, you see, this is not very easy to explain. I suppose what I’m looking to find out is whether or not there is a way to optimize this code, say, using one query?
Try:
You only need to include
A.course_idin the select portion if you care about the value.