简体   繁体   English

如何在多个列(例如2)上进行SELECT?

[英]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. 在方括号内进行这样的查询将为我提供2列的结果,我需要从其中一列中选择结果。 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. 为了在HAVING子句中使用SID,我需要在方括号内的SELECT运算符中包括它,这就是为什么我得到2列的原因。

You can't have 2 columns in an IN statement. IN语句中不能有2列。 You can just remove the SID from the select and only use it in the HAVING. 您可以从选择中删除SID,仅在HAVING中使用它。 You don't actually need to retrieve the data and your IN clause will work. 您实际上不需要检索数据,并且IN子句将起作用。

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. 感谢ZoharPeled提醒我以前的回答是错误的。

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: 您可以通过以下方式使用EXISTS

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 . ...必须为table找到的每一行运行EXISTS子句中的子查询。 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. 使用内部联接方法,RDBMS将对内联表执行一次sql,然后将结果保存在内存中以联接回另一个表。 For small tables this is fine - but for larger tables there could be a significant performance hit. 对于小型表,这很好-但是对于大型表,可能会严重影响性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM