I’m trying to select all fields in two separate tables as long as they’re sharing a common ID.
//mysql query
$result = mysql_query("SELECT * FROM project, links
WHERE project.id = links.id and project.id = $clientID")
//displaying the link
if ($row['url'] != null){
echo "<div class='clientsection' id='links'>Links</div>";
echo "<a class='clientlink' id='link1' href='" . $row['url'] . "'>" . $row['name'] . "</a>";
}
else {
echo "<a class='clientlink' id='link1' href='" . $row['url'] . "' style='display:none;'>" . $row['name'] . "</a>";
};
As you can see, my tables are “projects”, and “links” Each is sharing a common field “id” for reference. It looks as though where both links.id and project.id are equal, it outputs anything, but when there is no links.id associated with a given $clientID the container relative to the $clientID doesn’t display at all.
Essentially I’m using this to add links dynamically to a specific client in this CMS and if there are no links, I want the container to show up anyway.
Hopefully I’ve expressed myself clearly, any pointers in the right direction are appreciated. Thanks!
Using the SQL ANSI explicit join syntax, you can specify a
LEFT OUTER JOIN, as opposed to theINNER JOINthat you are doing in your implicit join.The LEFT OUTER JOIN returns results in the first table even if there are no matching rows in the joining table:
For rows where there is no matching id in the links table, links.id will be
NULL.Edit
If you want just the first link, where the autoincrement primary key links.linkid specifies the order, you can do a self join like this:
What this does is join in any links table rows where the linkid is smaller, and then exludes those rows in the WHERE clause. You end up with just the rows where there is no smaller linkid, hence the link with the smallest linkid for each project.