I have two tables in a mySQL database.
- milestones_all (PRIMARY KEY: MSID)
- user_transactions (FOREIGN KEY: MSID)
I am using the following code to query the tables:
$get_ms = db_query("SELECT * FROM milestones_all
LEFT JOIN user_transactions on user_transactions.MSID = milestones_all.MSID
WHERE milestones_all.MID=$MID
AND (user_transactions.tran_status IS NULL OR user_transactions.tran_status=3)
ORDER BY milestones_all.MSID ASC LIMIT 1"));
while($ms = $get_ms->fetch_assoc()){
$MSID = $ms['MSID'];
$ms_title = $ms['ms_title'];
}
Here is just the SQL:
SELECT * FROM milestones_all
LEFT JOIN user_transactions on user_transactions.MSID = milestones_all.MSID
WHERE milestones_all.MID=$MID
AND (user_transactions.tran_status IS NULL OR user_transactions.tran_status=3)
ORDER BY milestones_all.MSID ASC LIMIT 1
What I am trying to do is print out the data from milestones_all for any row that either
doesn’t have a user_transactions row attached to it or, if it does, the column tran_status in user_transactions is set to 3.
As of now, the query returns the proper results regarding which rows to return. ms_title is returned exactly how is should be. The problem is: MSID always returns blank. It is not blank in my database. Could this be because the LEFT JOIN is using the MSID column to find matches? Maybe there is a totally better way to do this?
Note: the db_query function does not interfere.
Yes, it’s because you have two columns named
MSID. If you change the join to useUSINGinstead ofON, it will collapse the two columns into one: