当多个条件匹配时,如何从sql-database读出数据

时间:2016-11-14 11:54:11

标签: mysql database

我有一个规范化的sql-database,有几个表和一个html-form来读出数据。有一个表包含产品特征,任何产品都可以具有一个或多个特征。

主表:product_main pm, 具有特征的表:product_characteristics pc, product_id是外键。

id | product_id | product_name | characteristic
1  | 27         | Product_C    | characteristic5 
2  | 27         | Product_C    | characteristic11
3  | 27         | Product_C    | characteristic3 
4  | 27         | Product_C    | characteristic47 
5  | 27         | Product_C    | characteristic34 
6  | 28         | Product_D    | characteristic29 
7  | 28         | Product_D    | characteristic63 
8  | 28         | Product_D    | characteristic2 

现在,我想读出符合所选条件的所有product_names。当只选择一个特征时,这样可以正常工作:

SELECT pm.name 
FROM product_main pm, product_characteristics pc 
WHERE pc.characteristic = 'characteristic47' 
  AND pm.id = pc.product_id

正确的结果是:Product_C。

如果同时选择多个特征,例如:

SELECT pm.name 
FROM product_main pm, product_characteristics pc 
WHERE pc.characteristic = 'characteristic47' 
  AND pc.characteristic = 'characteristic11' 
  AND pm.id = pc.product_id

没有结果,尽管Product_C符合这两个标准。 有人可以告诉我,我怎么能解决这个问题?

2 个答案:

答案 0 :(得分:0)

一个选项使用条件聚合:

SELECT product_id, product_name
FROM product_main
GROUP BY product_id, product_name
HAVING SUM(CASE WHEN characteristic = 'characteristic47' THEN 1 ELSE 0 END) > 0 AND
       SUM(CASE WHEN characteristic = 'characteristic11' THEN 1 ELSE 0 END) > 0

如果您还希望保留product_main中具有匹配特征的所有原始记录,则可以将上表连接回原始表:

SELECT t1.*
FROM product_main t1
INNER JOIN
(
    SELECT product_id
    FROM product_main
    GROUP BY product_id
    HAVING SUM(CASE WHEN characteristic = 'characteristic47' THEN 1 ELSE 0 END) > 0 AND
           SUM(CASE WHEN characteristic = 'characteristic11' THEN 1 ELSE 0 END) > 0
) t2
    ON t1.product_id = t2.product_id

答案 1 :(得分:0)

pc.characteristic同时不能同时为characteristic47characteristic11,但可能是(characteristic47characteristic11

所以像这样修改查询

SELECT pm.name 
FROM product_main pm, product_characteristics pc 
WHERE ( pc.characteristic = 'characteristic47' OR
        pc.characteristic = 'characteristic11' )
  AND pm.id = pc.product_id

你也应该像这样使用JOIN

SELECT pm.name 
FROM product_main pm
JOIN product_characteristics pc ON  pm.id = pc.product_id
WHERE ( pc.characteristic = 'characteristic47' OR
        pc.characteristic = 'characteristic11' )