This is My SELECT Query For searching user from the DB. The problem is I am only able to get the search result of those users who have posted any content in their postImg
table. Otherwise there is no user found. I want to search in such a way that even if any user has not posted any post then it should be found. I am using this query:
<?php
$sql = "SELECT * FROM postImg LEFT JOIN user ON postImg.userID=user.userID
WHERE user.userID='".$page_owner."' AND (userName LIKE '%".$searchVal."%') GROUP BY user.userID ";
$res3 = mysql_query($sql) or die(mysql_error());
while($row2=mysql_fetch_assoc($res3)){
echo $row2['userName']; // From user Table
echo $row2['likes']; // From postImg table
echo $row2['posts']; // From postImg table
} ?>
$sql = "SELECT * FROM postImg RIGHT JOIN user ON postImg.userID=user.userID
WHERE user.userID='".$page_owner."' AND (userName LIKE '%".$searchVal."%') GROUP BY user.userID ";
I think that you want user LEFT JOIN postImg
, not the other way around as you have it here.
The query as-written will return every record from postImg
whether-or-not it has an associated user
.
Obviously, you want every user
whether or not s/he has a postImg
.
Incidentally, I think that changing it to RIGHT JOIN
would work also, as Robert suggested in his answer. But, I can count on the fingers of one hand the number of times that I've seen a RIGHT
join . . . hence, I suggested flipping the table-names. ("Give 'em what they're used to.")
Edit: To clarify (for the benefit of the Peanut Gallery ...): these two forms of so-called "outer joins" are equivalent. The terms, LEFT
and RIGHT
, simply refer to which one of the two tables is the master ... "the one on the LEFT
side," before the word JOIN
, (postImg
in the query shown in the original post), or, "the one on the RIGHT
", after the word JOIN
. (user
) All of the rows in what I'm calling the "master" will be returned, along with whatever matching values in the "other" table as may be found.
For whatever reason, I very rarely find RIGHT
joins being used in production code. It's not that they can't be done, of course, but simply that I've observed that it isn't (usually) done.