简体   繁体   中英

How do I do SELECT on multiple colums(ex. 2)?

SELECT DName
FROM drugs
WHERE DID IN 
(
    SELECT DID,SID
    FROM transactions
    GROUP BY TotalCost
    HAVING SID = 1 AND TotalCost > 100
)

Doing such a query inside brackets will give me a result with 2 columns that I need to select results from one of them. In order to use SID in HAVING clause, I need to include it in SELECT operator inside brackets and that's why I am getting 2 columns as a result.

You can't have 2 columns in an IN statement. You can just remove the SID from the select and only use it in the HAVING. You don't actually need to retrieve the data and your IN clause will work.

If I understood you correctly then you want something like this:

SELECT DName
FROM drugs
WHERE (DID, SID) IN 
(
    //Subquery
)

Answer updated. Sorry i have been deleted my previous answer. And thanks to ZoharPeled for reminding that my previous answer's wrong.

If I understood your question, This should works for you :

SELECT DName
FROM drugs
WHERE DID IN (
    SELECT DID FROM(
        SELECT DID,SID,TotalCost
        FROM transactions
        GROUP BY TotalCost
        HAVING SID = 1 AND TotalCost > 100
    ) AS T
)

You can use EXISTS in the following way:

SELECT DName
FROM drugs
WHERE EXISTS
(
    SELECT *
    FROM transactions
    WHERE SID = 1 
    AND TotalCost > 100
    AND ( 
       drugs.DID = transactions.SID
       OR drugs.DID = transactions.DID
    )
)

You have a few answers there - but I'll throw an alternative option into the ring:

select DName
  from drugs d
 inner join (
                SELECT DID
                  FROM transactions
                 WHERE SID = 1 
                   AND TotalCost > 100
             ) tx on d.Did =tx.Did

I think (and I'm open to correction here) that if you use something like...

  select *
    from table
   where EXISTS in ( // some subquery )

... the subquery in the EXISTS clause must be run for each row found in table . With an inner join approach, the RDBMS will execute the sql for the inline table once and then hold the results in memory to join back to the other table. For small tables this is fine - but for larger tables there could be a significant performance hit.

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