0

How to write join query for PostgreSQL comma separated column join in PHP Laravel. FIND_IN_SET() will not work as I am using PostgreSQL:

enter image description here

I need to join Industry table with Company table. While company can have multiple industries they are entered in industry_id column and values are separated by comma.

FIND_IN_SET() will not work as I am using PostgreSQL

Mysql query:

$companyData = "SELECT comp.* 
                FROM companies AS comp 
                LEFT JOIN `industries` as `indus` ON find_in_set(indus.id, comp.indusrty_id) > 0           
                WHERE comp.id = ".$companyId;
5
  • 2
    What is the actual output you want here? Commented May 25, 2022 at 10:46
  • 1
    Looks like an error in your datamodel, multiple values in a single column (industry_id that is). Optimise your datamodel and your problem is also gone. Commented May 25, 2022 at 10:51
  • @TimBiegeleisen I need to join industry table with Company table. While company can have multiple industries they are entered in "industry_id" coloumn and values are separated by comma. FIND_IN_SET() will not works as I am using PostgreSQL Commented May 25, 2022 at 10:59
  • Great, what is the actual output you want here? Commented May 25, 2022 at 11:03
  • @TimBiegeleisen Question updated with Sql query Commented May 25, 2022 at 11:03

2 Answers 2

1

You may use the following trick on Postgres to workaround there being no FIND_IN_SET available:

SELECT comp.*
FROM companies AS comp
INNER JOIN industries AS indus
    ON ',' || comp.indusrty_id || ',' LIKE '%,' || indus.id || ',%'        
WHERE comp.id = ?;

Note that a much better solution here would be to fix your data model and stop storing CSV like this. Create a junction table in which each record stores one industry ID and one company ID.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your help. But this FIND_IN_SET will not works for Postgres
@SatheeshKumar Sorry, the reference to FIND_IN_SET was left there by accident, as I began my answer using your query as a starting point. The typo has been removed.
0

As a workaround you could also create your own PostgreSQL function find_in_set():

CREATE OR REPLACE FUNCTION FIND_IN_SET(text, text)
RETURNS BOOLEAN
IMMUTABLE
LANGUAGE SQL
AS
$$
    SELECT $1 =ANY(STRING_TO_ARRAY($2,','));
$$;

It doesn't fix the real problem nor the performance issues you're going to face, but it works.

Comments

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.