lets say i have first table like this
Branch table
|name |description|
|123456ABC|FOO |
|553646DEF|FO2 |
and second table like this
Balance table
|name|description|
|ABC |oof |
|DEF |2of |
i want to query to Balance table, where each row containing name from Branch table.. for example "123456ABC" in Branch table, i want to get "ABC" row from Balance table
how could i achieve that? i've tried this query so far with no luck
select * from Balance
where name like (
SELECT `name` FROM Branch
);
any suggestion?
Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with expression operator. It could be equality operator or comparison operator such as =, >, =, <= and Like operator. A subquery is a query within another query.
The PostgreSQL LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. The percent sign represents zero, one, or multiple numbers or characters.
Subqueries must be enclosed within parentheses. A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns. An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY.
In a SQL database query, a correlated subquery (also known as a synchronized subquery) is a subquery (a query nested inside another query) that uses values from the outer query. Because the subquery may be evaluated once for each row processed by the outer query, it can be slow.
You should convert the balance
's names to LIKE
patterns:
SELECT * FROM Balance
WHERE (
SELECT `name` FROM Branch
) LIKE '%' || name;
A join may look more readable:
SELECT b.* FROM Balance b JOIN Branch r ON r.name LIKE '%' || b.name;
I don't know if you will have dupes or not, so you may want to consider using a semi-join. For large datasets, a semi-join will typically be more efficient than an in-list query.
@clemens solution looks good, assuming no dupes. Alternatively, you can use regex:
select *
from balance ba
where exists (
select null
from branch br
where
br.name ~ ba.name
)
Performance-wise, I think like
will outperform the regex, but it's an option.
Also, if your string is always at the end, you can consider a join using right
or substr
:
select *
from balance ba
where exists (
select null
from branch br
where
right (br.name, length (ba.name)) = ba.name
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With