如何在MySQL中获取具有特定行/值的每个人的ID

时间:2018-06-07 14:17:22

标签: mysql

我有一张包含以下内容的表格:

|---------------------|------------------|
|     CustomerID      |     Product ID   |
|---------------------|------------------|
|          1          |         101      |
|---------------------|------------------|
|          1          |         102      |
|---------------------|------------------|
|          1          |         103      |
|---------------------|------------------|
|          2          |         101      |
|---------------------|------------------|
|          2          |         105      |
|---------------------|------------------|

我只想选择具有101,102,103产品ID的唯一客户ID。我不想使用ID 2来吸引客户,因为尽管他们有产品ID 101,但他们不会#39; t有正确的组合。

3 个答案:

答案 0 :(得分:1)

您的请求应该是:

Select CustomerID 
From your_table_name 
Where ProductID=101 And CustomerID In 
(Select CustomerID From your_table_name Where ProductID=102 And CustomerID In
(Select CustomerID From your_table_name Where ProductID=103));

答案 1 :(得分:1)

这应该有效:

SELECT CustomerID 
FROM myTables
WHERE ProductID IN(101,102,103)
GROUP BY CustomerID
HAVING COUNT(DISTINCT ProductID) = 3

答案 2 :(得分:0)

您还可以使用以下方法获得所需的结果

使用聚合

library(nlme)
library(lme4)

binary <- c(0,1,1,0,0,0,0,1,1,0)
continous <- c(0.2,0.21,0.23,0.25,0.14,0.2,0.21,0.23,0.25,0.14)
fixed_effect1 <- c("low","high","low","high","low","high","low","high","low","high")
fixed_effect2 <- c("rare","dense","dense","rare","dense","rare","dense","dense","rare","dense")
random_effect <- c(1,1,2,3,4,5,2,3,4,5)
dat <- data.frame(binary,continous,fixed_effect1,fixed_effect2,random_effect)
dat$binary <- as.factor(dat$binary)

mod <- glmer(binary~continous + fixed_effect1 + fixed_effect2 + (1|random_effect),  data = dat, family = binomial)

#Plot

ggplot(dat, aes(y=binary, x=continous)) + theme_bw() + geom_point()+
  xlab("Continous Variable") + ylab("Binary Variable")+ facet_grid(~fixed_effect1 + fixed_effect2)

使用EXISTS

SELECT CustomerID 
FROM table1
GROUP BY CustomerID
HAVING SUM(ProductID = 101) /* SUM(ProductID = 101) = SUM(CASE WHEN ProductID = 101 THEN 1 ELSE 0 END) > 0 */
   AND SUM(ProductID = 102)
   AND SUM(ProductID = 103);

Demo