有两个表产品,颜色 产品与颜色之间存在一对多关系。
产品表: ID,标题,说明
颜色表: ID,PRODUCT_ID,COLOR_NAME
现在我想做一个选择产品的查询,其中颜色表中包含所有(例如)三种颜色('红色','绿色' '褐色&#39)
答案 0 :(得分:0)
一种方法是:
select c.product_id
from colors c
where c.color_name in ('red', 'green', 'brown')
group by c.product_id
having count(distinct color_name) = 3;
答案 1 :(得分:0)
如果要从colors
表格中选择所有颜色,请尝试以下查询。
它将选择所有颜色,不限于3种颜色
SELECT c.product_id
FROM colors c
WHERE c.color_name IN (SELECT DISTINCT color_name FROM colors)
GROUP BY c.product_id
HAVING COUNT(DISTINCT color_name) = (SELECT COUNT(DISTINCT color_name) FROM colors);
如果您需要获取产品的标题和描述,那么:
SELECT * FROM products WHERE id in (
SELECT c.product_id
FROM colors c
WHERE c.color_name IN (SELECT DISTINCT color_name FROM colors)
GROUP BY c.product_id
HAVING COUNT(DISTINCT color_name) = (SELECT COUNT(DISTINCT color_name) FROM colors));
答案 2 :(得分:0)
HAVING是要走的路。
package com.example;
import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class CompletionIterator<T> implements Iterator<T>, AutoCloseable {
private AtomicInteger count = new AtomicInteger(0);
private CompletionService<T> completer;
private ExecutorService executor = Executors.newWorkStealingPool(100);
public CompletionIterator() {
this.completer = new ExecutorCompletionService<>(executor);
}
public void submit(Callable<T> task) {
completer.submit(task);
count.incrementAndGet();
}
@Override
public boolean hasNext() {
return count.decrementAndGet() > 0;
}
@Override
public T next() {
try {
return completer.take().get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
@Override
public void close() {
try {
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
executor = null;
completer = null;
count = null;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}