4

我有一张桌子,里面有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 作为其他行。

4

4 回答 4

3

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

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

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

于 2012-12-19T20:56:07.590 回答
1
select 
  a.itemID,
  a.name
from
  things a
where a.name in (
  select name
  from things b
  where b.itemID = '1'
)
于 2012-12-19T20:57:00.647 回答
1
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 子句来抑制明显的匹配。

于 2012-12-19T21:06:18.990 回答
0

如果您真的只有一张桌子,则无需将其带入两次UNION,或者像 htat 之类的任何花哨的东西。

SELECT 
    name
FROM
    a --assuming this is your only table
GROUP BY 
    itemID, name
HAVING
    itemID = '1'
于 2012-12-19T20:58:35.793 回答