Silverstripe LeftJoin WHERE两个值

时间:2014-06-28 13:45:41

标签: mysql sql silverstripe

我在班级客户和班级产品之间有很多关系。 例如

数据库客户

| ID  | Name  |
-----------------------
| 01 | Jack   |
| 02 | Joe    |
| 03 | Claire |

DB Pruduct

| ID  | ProductName |
---------------------------------
| 01 | watch        |
| 02 | pen          |
| 03 | car          |

因此,在dev / build之后,我得到一个名为Customer_Products的新数据库表,其中两个类的ID都是。 让我们说客户已经添加了一些像下面这样的产品 DB Customer_Products

| ID  | CutomerID | PruductID |
----------------------------------------------------
| 01 |  01        |  01       |    -> Jack added watch
| 02 |  02        |  01       |    -> Joe added watch
| 03 |  01        |  02       |    -> Jack added pen
| 04 |  01        |  03       |    -> Jack added car
| 05 |  03        |  01       |    -> Claire added watch

现在我想只显示添加手表和笔和汽车的客户(例如)。 所以我想使用查询只显示杰克,因为他添加了3个产品。这是我的问题/问题。 我的代码:

$sqlQuery = new SQLQuery();
$sqlQuery->setFrom("Customer"); 
$sqlQuery->addLeftJoin(' Customer_Products ','"Customer"."ID" = " Customer_Products "."CustomerID"');
$sqlQuery->addWhere("PruductID = 01  ");

// with this next two lines the result is empty, I know this is wrong but maybe this gives you an idea of what I m looking for. 
// $sqlQuery->addWhere("PruductID = 02 ");                  
// $sqlQuery->addWhere("PruductID = 03  ");     

$rawSQL = $sqlQuery->sql();
$rec = $sqlQuery->execute();

有一种方法可以通过一个查询执行此操作吗?或者我怎么做到这一点?感谢帮助!

1 个答案:

答案 0 :(得分:1)

有几种方法。我喜欢group byhaving方法,因为它最灵活:

select c.*
from customers c join
     customer_products cp
     on c.customerid = cp.customerid join
     products p
     on p.productid = cp.productid
where p.name in ('Pen', 'Car', 'Watch')
group by c.customerid
having sum(p.name = 'Pen') > 0 and
       sum(p.name = 'Car') > 0 and
       sum(p.name = 'Watch') > 0;

having子句中的每个条件都在测试是否存在一个产品。 where子句是可选的,但它可以帮助提高性能。