MSSQL 选择“垂直”-where

发布于 2025-01-05 12:40:45 字数 599 浏览 0 评论 0原文

除了“垂直位置”之外,我真的不知道如何解释。

想象一下下表:

TAGID|PRODUCTID|SHOP_ID
59   |3418-7   |38
61   |3418-7   |38
60   |4227-4   |38
61   |4227-4   |38

现在我想返回与标签 ID:59,61 相关的所有产品 ID。换句话说,两个标签 ID 都存在行的产品 ID 值。

所以我想返回 3418-7,但不是 4227-4

如何在 SQL 语句中尽可能简单地编写它?

这是我到目前为止的工作声明,但我觉得这可以通过更聪明的方式来完成:

SELECT 
  productid 
FROM shop_tag_relations 
WHERE 
  productid IN (select productid from shop_tag_relations WHERE tagid=59) 
AND 
  productid IN (select productid from shop_tag_relations WHERE tagid=61)
GROUP BY productid,shop_id

I don't really know how to explain except with "vertical where".

Imagine the following table:

TAGID|PRODUCTID|SHOP_ID
59   |3418-7   |38
61   |3418-7   |38
60   |4227-4   |38
61   |4227-4   |38

Now I want to return all product IDs, that have relation to the tag IDs: 59,61. In other words, values of product ID where rows exist for both tag IDs.

So I want to return 3418-7, but not 4227-4

How do I write this as simple as possible in a SQL statement?

This is the working statement I have so far, but I feel this could be done in a much smarter way:

SELECT 
  productid 
FROM shop_tag_relations 
WHERE 
  productid IN (select productid from shop_tag_relations WHERE tagid=59) 
AND 
  productid IN (select productid from shop_tag_relations WHERE tagid=61)
GROUP BY productid,shop_id

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

永言不败 2025-01-12 12:40:45
SELECT PRODUCTID
FROM T
WHERE TAGID IN (59,61)
GROUP BY PRODUCTID
HAVING COUNT(DISTINCT TAGID) = 2

或者

SELECT PRODUCTID
FROM T
WHERE TAGID = 59
INTERSECT
SELECT PRODUCTID
FROM T
WHERE TAGID = 61
SELECT PRODUCTID
FROM T
WHERE TAGID IN (59,61)
GROUP BY PRODUCTID
HAVING COUNT(DISTINCT TAGID) = 2

Or

SELECT PRODUCTID
FROM T
WHERE TAGID = 59
INTERSECT
SELECT PRODUCTID
FROM T
WHERE TAGID = 61
夏の忆 2025-01-12 12:40:45
SELECT DISTINCT 
a.PRODUCTID 
FROM mytable AS a
INNER JOIN mytable AS b ON a.PRODUCTID=b.PRODUCTID
WHERE a.TAGID=59
AND b.TAGID=61
;
SELECT DISTINCT 
a.PRODUCTID 
FROM mytable AS a
INNER JOIN mytable AS b ON a.PRODUCTID=b.PRODUCTID
WHERE a.TAGID=59
AND b.TAGID=61
;
忆离笙 2025-01-12 12:40:45
SELECT ProductId
FROM shop_tag_relations 
WHERE TAGID IN (59,61)
GROUP BY ProductId
HAVING COUNT(DISTINCT TagId) = 2
SELECT ProductId
FROM shop_tag_relations 
WHERE TAGID IN (59,61)
GROUP BY ProductId
HAVING COUNT(DISTINCT TagId) = 2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文