我有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