I have this SQL query:
SELECT MAX(a.date), d.group, c.name, b.name_id
FROM table1 a
LEFT JOIN table2 b ON a.id = b.id
LEFT JOIN table3 c ON b.name_id = c.name_id
LEFT JOIN table4 d ON b.group_id = d.group_id
WHERE a.foo = '12345'
GROUP BY d.group, c.name, b.name_id
ORDER BY MAX(a.date)
It returns something like this:
| date | group | name | name_id |
|---|---|---|---|
| yyyy-mm-dd 00:00:00 | FOOFOO | FA FA | 1 |
| yyyy-mm-dd 00:00:00 | FOOFOO | FA FA | 2 |
| yyyy-mm-dd 00:00:00 | FOOFOO | FA FA | 3 |
| yyyy-mm-dd 00:00:00 | FOOFOO | FA FA | 4 |
| yyyy-mm-dd 00:00:00 | FOOFOO | FA FA | 5 |
Focusing on name_id, I want to take all of them (about 800) and store them into an array-like variable. Then utilize said array-like variable in the following type of clause in separate SELECT statement:
SELECT COUNT(a.id)
FROM table999 a
WHERE a.foofoo IN @array
I've seen that you can build temporary tables that act as arrays, but I'm not sure if that's exactly what I'm looking for. I've also read that you can utilize variables (via @var) but it seems those can only hold one piece of data. Can what I'm looking for be done in SQL? Is there an array-like variable where I can push these name_id's to? Any help is super appreciated!
JOINorEXISTScould be more performant. Especially when you don't need all thoseJOINs from the original query to do that.JOINwill not work for this example. Already tried it and I received an incorrect count. The otherJOIN's are necessary in this example. RegardingEXISTShow would I specify whatname_id's I want in the subquery? If it's just use aWHEREclause with anINstatement, then I'd rather avoid all that work.