bonaca bonaca -3 years ago 90
MySQL Question

left join outputs incorrect first block of data

I'm trying to get data from two tables:

left join

$items = '';
$sql = "
SELECT as uid
, as uname
, as pid
, as pdate
, p.title as ptitle
, p.user as puser
FROM users u
JOIN posts p
ON = p.user
WHERE u.role = 'mod'
BY p.title;";

$stmt = $db->query($sql);
while($row = $stmt->fetch()){
$date = strtotime($row['pdate']);
$date = date("d-m-Y", $date);
$items.= "<div class='itemp' data-id=" . $row['pid'] . " data-user='" . $row['uname'] . "'>" .
"<span class='spandate'>" . $date . "</span>" .
"<span class='spantitle'>" . $row['ptitle'] . "</span>" .
"<span class='spanuser'>" . $row['uname'] . "</span>" .
echo $items;

Output is ok except first row where I see the date - 1.1.1970 - but there is no any row in
with that date. Plus - in the same row
is missing.

Also, is there a better way to create this query, avoiding
keyword ?

desired output (single block):

<div class='itemp' data-id=116 data-user='JOHN SMITH'><span class='spandate'>01-12-2017</span><span class='spantitle'>BLUE SKY</span><span class='spanuser'>JOHN SMITH</span></div>

Answer Source

Also, is there a better way to create this query, avoiding as keyword ?

Yes (but not better in my opinion):

FROM users
JOIN posts  
  ON = posts.user
WHERE users.role = 'mod'
  BY posts.title;

But as mentioned in the comments you have to modify your while loop in this case to get access to your values. But I think this is not a better way of writing this query cause it makes it harder to read.

Regarding your JOIN problem. this depends on what your result should be (I guess you only want users with posts ). So you should take a look at INNER JOIN instead of LEFT JOIN. You will get only results which also have posts entrys. Due to the nature of LEFT JOIN all entrys on the left table (in your case users) will be used, even if they donĀ“t have an entry in the posts table. INNER JOIN will only return results which match results in both tables.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download