0

Here is the query that almost works:

$query  = '';
$query .= ' SELECT highway_code.charge_id, 
        highway_code.act_abbr, 
        highway_code.short_form_wording, 
        highway_code.section, 
        highway_code.set_fine,  
        highway_code_arrest_jail_tow.demerits
        ';
$query .= ' FROM highway_code, highway_code_arrest_jail_tow ';
$query .= ' WHERE highway_code.charge_id = ? ';
$query .= ' AND highway_code.section = highway_code_arrest_jail_tow.section ';
$query .= ' AND highway_code.act_abbr = highway_code_arrest_jail_tow.act_abbr ';

The problem is that not all highway code charges have demerits, thus any charges without demerits are not returned, even though all the other fields apply. I would like to have all charges returned regardless if there is a value in highway_code_arrest_jail_tow.

2
  • You need a LEFT JOIN instead of the implicit INNER JOIN you have here (via comma-separated table names) Review codinghorror.com/blog/2007/10/… Commented Apr 17, 2013 at 13:20
  • Thank you for the link. I think that's the best explanation I've seen on the topic. However, as a novice with limited experience in creating SQL statements, I'm not sure how i'd write it out... I'm starting to do the research now, but if the solution is simple, would you mind posting? Tks! Commented Apr 17, 2013 at 13:30

1 Answer 1

2

The use of comma-separated tables in the FROM clause as you have it, with an equality condition between the related columns implies an INNER JOIN. To enforce all records being returned from the primary table regardless of the presence of related records in the related table, use a LEFT JOIN instead.

I'll replace your implicit inner join with an explicit LEFT JOIN:

SELECT
  highway_code.charge_id, 
  highway_code.act_abbr, 
  highway_code.short_form_wording, 
  highway_code.section, 
  highway_code.set_fine,  
  highway_code_arrest_jail_tow.demerits
FROM
  highway_code
  LEFT JOIN highway_code_arrest_jail_tow
     /* Two relating conditions belong in the ON clause */
     ON highway_code.section = highway_code_arrest_jail_tow.section
     AND highway_code.act_abbr = highway_code_arrest_jail_tow.act_abbr
WHERE
  /* and the filtering condition remains in the WHERE */
  highway_code.charge_id = ?
Sign up to request clarification or add additional context in comments.

1 Comment

You sir, are amazing. I was so close, it was the WHERE at the end I was juggling with. Thank you so much Michael.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.