简体   繁体   中英

SQL Select from table using the outcome of a previous SELECT query?

Basically, I want to Select from one table, then using the outcome select from another table and then finally echo the values I selected.

DECLARE @var1 int; /*This should become the result of Table1.Column1 */
DECLARE @var2 nchar(50); /*This should become the result of Table1.Column2 */
DECLARE @var3 nchar(50); /*This should become the final result */

SELECT @var1 = (SELECT Column1 FROM Table1 WHERE Column3 = '12345')
SELECT @var2 = (SELECT Column2 FROM Table1 WHERE Column3 = '12345')

SELECT Column1 FROM Table2 WHERE Id = @var1

Then once this has finished, PHP echo var1, var2 and var3.

I know this would be easier with 2 seperate queries but I want to keep it clean and not have to do that, does anyone know how I can do this? I know the code I provided is completely off but hopefully it makes sense what I'm trying to do.

This is what a join is for. Your first two example SELECT statements can be combined into a single statement like:

 SELECT column1, column2 FROM table WHERE column3 = '12345';

You can then JOIN your table2 :

SELECT
    t1.column1,
    t1.column2,
    t2.column1
FROM Table1 T1
    LEFT OUTER JOIN Table2 T2
        ON t1.column2 = t2.id
WHERE t1.Column3 = '12345';

Using a LEFT OUTER JOIN here since that is the type of join that foots best with your psuedo code above. Essentially "SELECT all records that match the WHERE criteria from table1 and any records that might also match from table2 based on that ON condition. If no records match in Table2 for that ON Condition then just return NULL for that table2 column".

The result set returned will have three fields which are functionally equal to your @var1 , @var2 and @var3

You can do this in two ways. Since it seems that your first query returns a single result, you can use that subselect as the expression in your second query:

SELECT @var2 = (SELECT Column2 FROM Table1 WHERE Column3 = (SELECT Column1 FROM Table1 WHERE Column3 = '12345'))

or you could use a common table expression (I'm assuming SQL Server):

with CTE_Table (var1) as
(SELECT Column1 FROM Table1 WHERE Column3 = '12345')
SELECT @var2 = (SELECT Column2 FROM Table1 WHERE Column3 = (select var1 from CTE_Table))

Something of that circumference should work. I just entered that here for context, but have not tested for syntax.

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