如何查找其他字段中数据的唯一字段?

时间:2016-06-06 11:49:49

标签: mysql sql

为了概括,我有一个与以下结构类似的数据库:

CustomerDatabase
ProductID  | ProductName | CustomerID | Gender |
008100     | Laptop      | 1          | Male   |
008101     | Desktop     | 2          | Female |
008100     | Laptop      | 3          | Female |
008102     | Printer     | 4          | Male   |
008101     | Desktop     | 5          | Female |

我可以运行什么声明来显示仅由特定性别而非另一种性别购买的产品ID?

示例结果如下:

ProductID | Gender | CustomerID|
008101    | Female | 2         |
008101    | Female | 5         |

因为产品“008101”仅由女性而非男性购买。

提前致谢。

3 个答案:

答案 0 :(得分:1)

另一种方法是对Female大于Female的事实使用单select t.productid from YourTable t group by t.productid having MAX(t.gender) = 'Female' 个中继,因此如果最大值为{{1}},那么它是唯一的之一。

{{1}}

答案 1 :(得分:0)

您可以使用聚合和having

获取产品ID
select productid
from t 
group by productid
having min(gender) = max(gender) and min(gender) = 'F';

您可以使用joininexists获取原始表格中的行:

select t.*
from t join
     (select productid
      from t 
      group by productid
      having min(gender) = max(gender) and min(gender) = 'F'
     ) tf
     on t.productid = tf.productid;

答案 2 :(得分:0)

要仅让productID女性订购,您可以

select productid
from your_table
group by productid
having sum(gender = 'Male') = 0

并且只能获得productID仅订购的单一性别

select productid
from your_table
group by productid
having count(distinct gender) = 1