Question

I'm executing a query with a LEFT JOIN with an ON clause, but it doesn't appear to be acting correctly.

Relevant schema:

cdrs

id [primary key - auto incrementing]
aparty [VARCHAR(50)]
bparty [VARCHAR(50)]

rates

id [primary key - auto incrementing]
apartypattern [VARCHAR(50)]
bpartypattern [VARCHAR(50)]

There may be multiple patterns that match a cdr. A pattern is considered matched if, reading left to right, all characters of the pattern are present in order from the beginning in the relevant cdr field. Where mulitple matches are present, the logic to describe the match criteria could be expressed as:

ORDER BY LENGTH(bpartypattern), LENGTH(apartypattern) LIMIT 1

I'm trying to achieve this with the following query:

SELECT c.id, r_a.id
FROM cdrs c
LEFT JOIN (
  SELECT id, LENGTH(apartypattern) AS maxlen, apartypattern
  FROM rates
) r_a ON c.aparty LIKE CONCAT(r_a.apartypattern,'%')
LEFT JOIN (
  SELECT id, LENGTH(bpartypattern) AS maxlen, bpartypattern
  FROM rates
) r_b ON c.bparty LIKE CONCAT(r_b.bpartypattern,'%')
WHERE r_a.id = r_b.id
GROUP BY c.id
ORDER BY r_b.maxlen DESC, r_a.maxlen DESC

But the results I'm getting are identical to if I had have replaced the WHERE clause with:

WHERE r_a.id = 1 AND r_b.id = 1

After manual inspection of the data set, there are obvious rows that should have matched that didn't.

As a further troubleshooting step, I tried simplifying the query as follows, still getting results as if that alternative WHERE clause was being applied:

SELECT c.id, r_a.id
FROM cdrs c
LEFT JOIN (
  SELECT id, LENGTH(aparty) AS len, apartypattern
  FROM rates
) r ON c.aparty LIKE CONCAT(r_a.apartypattern,'%')
Was it helpful?

Solution

SELECT 
c.id, 
r.id
LENGTH(r.apartypattern) as `r_l`,
LENGTH(r.bpartypattern) as `r_b`
FROM cdrs c
LEFT JOIN rates r ON c.aparty LIKE CONCAT(r.apartypattern,'%') AND
                     c.bparty LIKE CONCAT(r.bpartypattern,'%')
ORDER BY `r_l` DESC, `r_b` DESC
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top