用where子句分组,其中两个表达式都必须正确


Group by with where clause where both expressions have to be correct?

我有一个表productsartistsartist_product。一个产品可能来自多个艺术家,所以artist_product表会显示

id = 1
product_id = 1
artist_id = 1
id = 2
product_id = 1
artist_id = 2

我现在想要的是得到所有由同一艺术家制造的产品。因此,所有来自Artist 1Artist 2但不是其他人(例如第三位艺术家)的产品

假设我有艺术家1和艺术家2,如上面解释的"表"中所示。我正在查看id为1的产品。现在,我想拥有由同一艺术家制作的所有其他产品(例如产品2、3、4等),但不是来自其他艺术家,也不是当前产品。

我写了这个查询

SELECT p.title, ap.product_id 
FROM artist_product ap 
INNER JOIN product p ON p.id = ap.product_id 
GROUP BY product_id 
HAVING COUNT(*) > 1;

现在我得到了所有有不止一个艺术家的产品,对吗?但问题是,我现在只从多位艺术家那里获得产品,我现在也需要检查艺术家。我不能做artist_id = x AND artist_id = x,因为由于分组的原因,这不起作用,我也不能做artist_id = x OR artist_id = x,因为这不一样。

我需要解决这个问题,也需要知道我将如何在条令中解决这个问题?我目前没有ArtistProduct的类,我需要创建一个并这样做吗?

$qb = $em->getRepository(''namespace'Product')->createQueryBuilder('p');
$artists = $this->getArtists();
$qb->innerJoin('ap.artist_product', 'a', 'WITH', 'a.id IN (:artists)')
    ->setParameter('artists', $this->getArtists())
    ->setMaxResults(12);
$qb->andWhere('p.id != ' . $this->getId());
return $qb->getQuery()->getResult();

这看起来不对,一定是我少了什么东西。通常情况下,我会先在SQL中创建查询,然后在Doctrine中创建查询。但我甚至没有正确执行查询。

SELECT p.id, p.title, ap2.product_id, count(*) c
-- first select what we want - product
FROM product p 
-- it must have both artists
INNER JOIN artist_product ap 
  ON p.id = ap.product_id AND ap.artist_id IN (?, ?)
-- catch any other artist
LEFT JOIN artist_product ap2
  ON p.id = ap2.product_id AND ap2.artist_id NOT IN (?, ?)
GROUP BY p.id 
-- and exclude the product, if it has one
HAVING ap2.product_id IS NULL 
-- there must also be exactly 2 artists
AND c = 2;