简体   繁体   中英

Use results in one column on a SQL table to search another table

I was just after an elegant solution to what I'm doing rather than just manually copying and pasting into each SELECT query.

I have a list of 200+ string results from one table.

SELECT name FROM accounts

Which gives me results like:

name
$string1$
$string2$

I want to then search each result in another query on another table to get a COUNT. Doing this manually one by one, I would run:

SELECT COUNT(DISTINCT table.id) FROM table WHERE table.code LIKE '%$string1$%'

I want to be lazy and achieve this via SQL if possible where I end up with something like this:

accounts.name Count
$string1$ 5699
$string2$ 245

Any advice or help would be most welcome!

It sounds like you'd want to join on a LIKE operator, and then count the results:

  ;WITH matches_on_account_name AS (
        SELECT a.[name] AS account_name
          FROM accounts AS a
          JOIN [table] AS t ON t.[code] LIKE '%' + a.[name] + '%'
  )
  SELECT account_name,
         COUNT(*) AS num_accounts
    FROM matches_on_account_name
GROUP BY account_name;

One option that should work on pretty much every RDBMS is a correlated subquery

select a.name, (
  select Count(*) 
    from table t 
    where t.code like Concat('%',a.name,'%')
) as Count
from accounts a

Using CONCAT for sticking the % to the name.

And defaulting the NULL names to something unmatchable.
Just preventing that name LIKE '%%' would match everything.

SELECT 
  acc.name AS account_name
, COUNT(DISTINCT tbl.id) AS total_uniq_table_id
FROM accounts  AS acc
JOIN yourtable AS tbl
  ON tbl.code LIKE CONCAT('%',COALESCE(acc.name,'D§OUOSVAVV§M'),'%') 
GROUP BY acc.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM