Jump to content

Mysql LEFT JOIN help, please


kid_drew

Recommended Posts

Hey guys,
I'm having a problem with a left join statement.  When I query the database from the phpmyadmin console, it works fine, but I'm having problems with the mysql_query call in php.  The query is:

"select * from users left join images on users.username = images.username AND images.list_order = 0"

This is supposed to grab all users whether they have images or not, but if they do, the images fields should be populated instead of NULL.  if the user has an image listed in the "images" table, everything works fine.  The problem is that if the user does not have an image listed in table "images", then the username field returns NULL.  Again, the query looks like it works perfectly if I do it from the phpmyadmin console, but not in PHP.

Any ideas?
Link to comment
Share on other sites

The images.username field is overriding the user.username field. A quick fix would be the following
[code]
SELECT
u.username AS uname, u.*, i.*
FROM
users AS u
LEFT JOIN
images
ON
u.username = i.username
AND i.list_order = 0
[/code]
You'd now access the username in the column uname rather than username. You can also list all the columns you'd like from each table (users.column1, images.column1 ...) instead of using "*" to avoid the problem.

[url=http://www.php.net/mysql_fetch_assoc]mysql_fetch_assoc[/url]
[url=http://www.php.net/mysql_fetch_array]mysql_fetch_array[/url]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.