0

Trying to get results from 5 tables where the userId is the same. I am getting like 8k rows for where there should be about 20-30 or so. Here is my statement:

mysql_query("SELECT * FROM userrating, postratings, blogCommentRatings, commentratings, gamecommentratings WHERE userrating.userId = '$this->userId' AND postratings.userId = '$this->userId' AND blogCommentRatings.userId = '$this->userId' AND commentratings.userId = '$this->userId' AND gamecommentratings.userId = '$this->userId'") or die(mysql_error());

I am getting results like a cross join where every combination of rows possible is coming back. I know there is some sort of JOIN that may help me can anyone give me some advice?

4
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by tyson.crouch
0

Only the first condition should refer to the variable, the rest should really be along the lines of

AND tablename2.id=tablename1.id
AND tablename3.id=tablename2.id

etc

And you have to check your ERD to chain the tables in the correct order.

Although JOIN terminology is the preferred way to express things, WHERE will do exactly the same thing (although using the JOIN syntax makes some things easier to express)

Not sure why you're getting so many more rows, but for a cross join you'd get rows in tableA X rows in TableB X etc.

0

your problem is that you are using a cross join which will return n^n results. You should use an inner (natural) join to return rows with all matching results.

SELECT *
FROM 
-- Join #1
(
        -- Join #2
	(userrating INNER JOIN postratings USING(userID) )

	INNER JOIN

        -- Join #3
	(blogCommentRatings INNER JOIN commentratings USING(userId) )

	USING(userID)

)
-- Join #4
INNER JOIN gamecommentratings 
USING(userId)

try using the above FROM clause to join all of your tables

Edited by tyson.crouch: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.