I’ve two tables like below
Table 1 : users
id – number
authorization – json
id | user_name | authorized_customers |
---|---|---|
1 | user1 | ["002001A", "002001B","002001ABC"] |
2 | user2 | ["002001A", "002001Z","002001ABZ"] |
Table 2: orders
id – number,
user_id – number – forigen key of users table
name – varchar
customer – varchar
id | customer_name | customer |
---|---|---|
1 | john | 002001A |
2 | doe | 002001Z |
My question is:
How do I get all orders based on the user1’s authorized customer like
select * from orders where customer in(select CAST(json_array_elements(authorized_customers) AS VARCHAR) AS customer_ids from users where id=1)
Any help is appreciated.
I tired above query but no value returned
3
Answers
Postgres supports a number of operators for dealing with JSON; in this case you can use the
json ? text -> boolean
operator as described in the official docs.Something like:
will return records where the o.customer value is in the JSON array u.authorized_customers.
you can try this
make sure that you have db indexes on
users.id
andorders.customer
columns. It can greatly improve the performance.How does
json_array_elements_text
work?:example users data:
query like:
will make this output:
Go with json_array_elements_text function. It will extract the data from the array.
Here is how to execute query:
The join is being performed on basis of
o.customer = ANY(json_array_elements_text(u.authorized_customers))
Value is returned if any of the value matches.