Is it possible for a subquery to return two values?
Asked Answered
F

4

7

Is it possible for a subquery to return two values onto the outer query? Such as:

SELECT 1, 
       (SELECT COUNT(*), MAX(*) FROM test_table WHERE test=123) 
FROM another_table

Or is there a better way to do this?

Ferne answered 20/12, 2010 at 0:36 Comment(1)
If Another_Table has 20 rows, you'd get 20 rows of output containing the same data, unless the column test is present only in Another_Table and not in Test_Table (in which case, it is a funny way of writing the restriction (which is a fairly extreme example of 'meiosis').Lulululuabourg
C
8

If you use the subquery in the FROM clause rather than the field list, then you can treat the output as a table and refer to the separate columns.

Copybook answered 20/12, 2010 at 0:39 Comment(5)
I'm a bit confused by that. Can you explain a bit further, please?Ferne
SELECT A.a, A.b FROM (SELECT a, b FROM MyTable) AS A;Keilakeily
@kevin Your subquery, can go as an additional table in the FROM clause with an alias (eg. AS test_t, name the fields in the subquery too), and refer to the values in the field list: SELECT 1, test_t.count, test_t.max FROM (SELECT ...Copybook
Only issue here is that without join criteria, this suggestion will produce a cartesian product.Wiebmer
@OMG Ponies: Quite right, it needs restricting. If the queries are disjoint, then it might be better as two subqueries in the field list. OP only asked if it was "possible for a subquery to return two values onto the outer query" - answer, yes. Suitability was not accounted for.Copybook
G
1

You are just selecting numbers as results so couldn't you just do:

SELECT 1, COUNT(*), MAX(*) FROM test_table WHERE test=123
Gravimetric answered 20/12, 2010 at 0:38 Comment(1)
They're two different tables :\Ferne
C
0

Not possible

mysql> select 1, (select 2, 3) from dual;
ERROR 1241 (21000): Operand should contain 1 column(s)

If you are dealing with two tables and you what the results in one line, you should preform a join.

Condition answered 20/12, 2010 at 0:39 Comment(0)
P
0

Hmm, it depends on what exactly you want to do with the data, you can join two tables using JOIN syntax, and one of the tables can actually be a subquery. I think that is probably what you want.

I'm not even user what your current query will do..

Documentation: http://dev.mysql.com/doc/refman/5.0/en/join.html

Photograph answered 20/12, 2010 at 0:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.