Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql Silverstripe LeftJoin,其中两个值_Mysql_Sql_Silverstripe - Fatal编程技术网

Mysql Silverstripe LeftJoin,其中两个值

Mysql Silverstripe LeftJoin,其中两个值,mysql,sql,silverstripe,Mysql,Sql,Silverstripe,我在班级客户和班级产品之间有很多关系。 比如说 数据库客户 | ID | Name | ----------------------- | 01 | Jack | | 02 | Joe | | 03 | Claire | 德布罗德 | ID | ProductName | --------------------------------- | 01 | watch | | 02 | pen | | 03 | car | 因此,

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

数据库客户

| ID  | Name  |
-----------------------
| 01 | Jack   |
| 02 | Joe    |
| 03 | Claire |
德布罗德

| ID  | ProductName |
---------------------------------
| 01 | watch        |
| 02 | pen          |
| 03 | car          |
因此,在开发/构建之后,我得到了一个名为Customer_Products的新DB表,其中两个类的ID都是。 假设客户添加了以下产品 DB客户产品

| 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
现在,我只想展示添加了手表、钢笔和汽车的客户(例如)。 所以我想用一个查询只显示Jack,因为他添加了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();

有没有一种方法可以通过一个查询来实现这一点?或者我怎么能做到?谢谢你的帮助

有几种方法。我喜欢
分组方式
拥有
的方式,因为它是最灵活的:

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
子句是可选的,但它有助于提高性能。

这样可以使用多个TableJoin吗?或者我应该使用WHERE而不是Group by and have?@user3786012。我不明白你的问题。我的意思是当我必须检查其他表。例如:还有表地址、设置等。我想查询以下内容:显示添加了产品01、02和03并居住在Ardess.City='London'且具有设置的所有客户。xyz='x'等等。@user3786012。当然条件可以来自任何表。