Question

I need to join two tables where a substring of the base table's join column's value is used to join with the other table.

I'm using zend framework 2 and I've written the query as follows.

$select = new Select($this->table);

$select->columns(array('match_code'))
           ->join('countries','countries.cid = SUBSTR(matches.teams,1,3)', 'name')
           ->where(array('round'=>1));

This gives an error.

SQLSTATE[42000]: Syntax error or access violation: 1630 FUNCTION mydatabase.SUBSTR does not exist. 
Check the 'Function Name Parsing and Resolution' section in the Reference Manual

I've run the mysql query corresponds to this and it works perfectly.

SELECT `matches`.`match_code`, `countries`.`name` 
FROM `matches` INNER JOIN `countries` 
ON `countries`.`cid`=SUBSTR(`matches`.`teams`,1,3) 
WHERE `round` = 1

I cannot use Zend\Db\Sql\Expression in here as the join() expects only a string.

Any suggestions??

Was it helpful?

Solution

I have solved this issue by using Zend\Db\Sql\Expression in the ON clause of join().

$select->columns(array('match_code'))
           ->join('countries',new \Zend\Db\Sql\Predicate\Expression('countries.cid = SUBSTR(matches.teams,1,3)'), 'name')
           ->where(array('round'=>1));

Thanks to @Crisp for the suggestion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top