Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining SQL queries

Tags:

sql

mysql

Right now I'm running

SELECT formula('FOO') FROM table1
WHERE table1.foo = 'FOO' && table1.bar = 'BAR';

but I would like to run this not on the constant FOO but on each value from the query

SELECT foos FROM table2
WHERE table2.bar = 'BAR';

How can I do this?

Edit: Important change: added FOO to the arguments of function.

Illustration:

SELECT foo FROM table1 WHERE foo = 'FOO' && table1.bar = 'BAR';

gives a column with FOOa, FOOb, FOOc.

SELECT formula('FOO') FROM table1
WHERE table1.foo = 'FOO' && table1.bar = 'BAR';

gives a single entry, say sum(FOO) (actually much more complicated, but it uses aggregates at some point to combine the results).

I want some query which gives a column with sum(FOO1), sum(FOO2), ... where each FOOn is computed in like manner to FOO. But I'd like to do this with one query rather than n queries (because n may be large and in any case the particular values of FOOn vary from case to case).

like image 667
Charles Avatar asked Sep 06 '11 19:09

Charles


People also ask

What is SQL chaining?

Cross-database ownership chaining, also known as cross-database chaining, is a security feature of SQL Server that allows users of databases access to other databases besides the one they are currently using.

Can SQL queries run in parallel?

SQL Server has the ability to execute queries using multiple CPUs simultaneously. We refer to this capability as parallel query execution. Parallel query execution can be used to reduce the response time of (i.e., speed up) a large query.

Does SQL run sequentially?

SQL is not a traditional programming language in which you write a sequence of instructions in a given order of execution. Instead, SQL is a "declarative" language, which means that by writing a SQL query, you declare what data you expect as a result of the query, but you don't indicate how to obtain it.


2 Answers

Try this one:

SELECT formula FROM table1
WHERE table1.foo IN(SELECT foos FROM table2
WHERE table2.bar = 'BAR';
) AND table1.bar = 'BAR';
like image 86
Brian Glaz Avatar answered Sep 21 '22 18:09

Brian Glaz


SELECT formula FROM table1 WHERE bar = 'BAR' AND foo IN (SELECT foos FROM table2 WHERE bar = 'BAR');

EDIT:

This isn't tested, but perhaps this will work?

SELECT formula(q1.foo) FROM table1 INNER JOIN (SELECT foo, bar FROM table2) q1 ON table1.foo = q1.foo WHERE table1.bar = 'BAR';
like image 45
Travesty3 Avatar answered Sep 21 '22 18:09

Travesty3