我有如下 2 个 MySQL 表;
下面的查询为我提供了具有
tagId
1450 OR
1451 的所有产品。
我的问题是;我需要找到具有 tagId
1450 AND
1451 的产品。正确的方法是什么?
SELECT * FROM products AS PROD
LEFT JOIN product_tags AS PTAG ON PTAG.productGuid = PROD.productGuid
WHERE PTAG.tagId IN (1450, 1451)
CREATE TABLE `products` (
`productGuid` varchar(36) NOT NULL,
`productName` longtext NOT NULL,
PRIMARY KEY (`productGuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `product_tags` (
`productGuid` varchar(36) NOT NULL,
`tagId` int NOT NULL,
`id` int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
KEY `idx_productGuid` (`productGuid`),
KEY `idx_tagId` (`tagId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
我以前尝试过类似的方法,希望这有帮助!
SELECT *
FROM
products AS PROD
LEFT JOIN
(select productGuid from product_tags pt
where pt.tagId=1450
and 1=(select distinct 1 from product_tags where pt.productGuid=productGuid and tagId=1451)
)AS PTAG
ON PTAG.productGuid = PROD.productGuid;