[英]MySQL Query - multiple WHERE clause on 1 column
誰能幫我根據下面的查詢建立一個查詢。
如您所見,我有一個產品,其中包含在前端建立的規格和某些組。 我知道問題所在,1 列不能同時為 2 個值,但我只需要這 2 個組中的那些產品。
為了說明,product_specification_sid,id 2 3 和 4 是尺寸,de rest 8 ~ 11 是 colors,所以我想 Z99938282F04071845941E18F216 的產品。
由於組(大小、顏色)將來可能會有所不同,因此不能選擇內部加入雙表。
SELECT
products.*,
categories.*,
manufacturers.*
FROM products
INNER JOIN product_categories ON product_category_pid = product_id
INNER JOIN categories ON product_category_cid = category_id
INNER JOIN manufacturers ON product_manufacturer = manufacturer_id
INNER JOIN product_specifications ON product_specification_pid=product_id
WHERE
product_active = 1
AND
(
product_specification_sid in (3)
AND
product_specification_sid in (8,9,6,7,10,11)
)
GROUP BY product_id
您可以改用 having 子句。
SELECT
products.*,
FROM products
INNER JOIN product_categories ON product_category_pid = product_id
INNER JOIN categories ON product_category_cid = category_id
INNER JOIN manufacturers ON product_manufacturer = manufacturer_id
INNER JOIN product_specifications ON product_specification_pid=product_id
WHERE product_active = 1
GROUP BY product_id
HAVING COUNT(CASE WHEN product_specification_sid in (3) THEN 1 END) > 0
AND COUNT(CASE WHEN product_specification_sid in (8,9,6,7,10,11) THEN 1 END) > 0
據我了解,您正在尋找具有滿足特定條件的兩個匹配 product_specification 記錄的產品記錄。 在我看來,簡單的解決方案是:
SELECT products.*, categories.*, manufacturers.*
FROM products
INNER JOIN product_categories ON product_category_pid = product_id
INNER JOIN categories ON product_category_cid = category_id
INNER JOIN manufacturers ON product_manufacturer = manufacturer_id
INNER JOIN product_specifications ps1 ON ps1.product_specification_pid=product_id
INNER JOIN product_specifications ps2 ON ps2.product_specification_pid=product_id
WHERE product_active = 1
AND ps1.product_specification_sid in (3)
AND ps2.product_specification_sid in (8,9,6,7,10,11)
順便說一句,那個“分組依據”是行不通的。 您必須按非聚合的所有內容進行分組,並且每個表必須至少有一個列,因此您至少有三個非聚合。 (好吧,也許 MySQL 在這里有一些擴展,但在標准 SQL 中是需要的。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.