我有3个表,products
,productscategories
和categories
。Mysql组与多列内连接
productscategories
是一个多对多的表,只有其他两个表的id号。
没有GROUP BY看起来像这样的结果:
id | Url | Category
-------------------------------------
1 | http://example.com/12 | hat
2 | http://example.com/12 | shoe
3 | http://example.com/13 | hat
4 | http://example.com/13 | jacket
5 | http://example.com/14 | hat
6 | http://example.com/14 | socks
现在我想排除的每一行与同url
如果它包含任何已选定的类别,在这种情况下jacket
和shoe
。
不需要的结果是这样的:
id | Url | Category
-------------------------------------
1 | http://example.com/12 | hat
3 | http://example.com/13 | hat
5 | http://example.com/14 | hat
因为url
id为13包括jacket
我不想在那儿。 url
与14相同,其中包括shoe
。
这是因为我有多个类别和多个不知道对方的网址。
用SQL的上述:
SELECT * FROM products
JOIN productscategories ON products.id = productscategories.product_id
JOIN categories ON categories.id = productscategories.category_id
WHERE categories.slug NOT IN (
'shoe',
'jacket',
)
GROUP BY products.image_url
的通缉的结果:
id | Url | Category
-------------------------------------
5 | http://example.com/14 | hat
我怎样才能使一个SQL查询,使URL意识到类的,像上面?
这是一个奇怪的寻找答案,但它在我的测试中很有用,它也很快闪烁(比其他答案快30-60倍)。没有陷阱?谢谢! –
@JensTörnell在MySQL上的工作正常。在其他RDBMS可能需要'sum(case when categories.slug IN('shoe','jacket')then 1 else 0 end)'' – Mike