【问题标题】:SQL - passing variable from first select to second selectSQL - 将变量从第一个选择传递到第二个选择
【发布时间】:2012-12-20 06:14:15
【问题描述】:

我有一张things 的桌子,里面装满了ItemID 列出的项目。给定一个 ItemID,我需要获取具有 ItemID 的记录以及具有相同 name 的所有其他项目。

在下面的示例数据中,给定 ItemID 为 1,我需要选择与 ItemID 1 同名的所有记录(在本例中为“poptarts”),包括 ItemID 为 1 的记录。

ItemID = 1 name = poptarts
ItemID = 7 name = poptarts
ItemID = 8 name = cheddar
ItemID = 323 name = poptarts

select a.ItemID, a.name from things where a.ItemID = '1'
UNION
select b.ItemID, b.name from things where b.name = a.name

我上面写的 SQL 并没有将 a.name 传递给第二个选择。有没有办法将名字值传递给第二个选择?我希望语句返回 itemid = 1 作为第一行,7 和 323 作为其他行。

【问题讨论】:

  • 你必须在哪里试试这个?

标签: sql select


【解决方案1】:

UNION 仅真正用于连接两个不同的集合。根据您的示例,您可能可以执行以下操作:

SELECT a.ItemID, a.Name
FROM things a
WHERE name IN (SELECT name FROM things WHERE itemID = 1)

有很多方法可以编写这种查询,具体取决于您使用的 SQL 风格,但这应该或多或少是通用的。

【讨论】:

  • 返回每一行。 ItemID 1,ItemID 2,ItemID 3,所有项目都有不同的名称。
  • 那么,如果您取出子查询并输入name 值,即SELECT a.itemID, A.name FROM Things a WHERE Name = 'poptarts',会发生什么情况
  • 返回我想要的,而不是通过传入的项目 ID。
  • 如果你只运行子查询,如果是这样,你会得到“poptarts”,仔细检查复制/粘贴,如果 itemID 在你的表中是唯一的,可以考虑用“=”替换“IN”(尽管这不应该有所作为)
  • 如果我运行子查询,我只会得到 ItemID = 1 的行。
【解决方案2】:
select 
  a.itemID,
  a.name
from
  things a
where a.name in (
  select name
  from things b
  where b.itemID = '1'
)

【讨论】:

    【解决方案3】:
    SELECT this.name, this.id, that.id
    FROM thing this
    LEFT JOIN thing that ON that.name=this.name AND that.id <> this.id
    WHERE this.id = 1
       ;
    

    注意:这也会选择没有孪生记录的 this-rows;在这种情况下,that.id 将为 NULL。如果您想抑制没有双记录的记录,请删除 LEFT

    更新:添加了 id id 子句来抑制明显的匹配。

    【讨论】:

      【解决方案4】:

      如果你真的只有一张桌子,没必要把它带进来两次,UNION,或者像 htat 这样的花哨的东西。

      SELECT 
          name
      FROM
          a --assuming this is your only table
      GROUP BY 
          itemID, name
      HAVING
          itemID = '1'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-04
        • 2016-11-07
        • 2020-04-27
        • 2010-12-21
        • 2018-10-12
        • 1970-01-01
        • 1970-01-01
        • 2015-08-25
        相关资源
        最近更新 更多