[英]mysql FROM clause with subquery in Cakephp 3
I want to use subquery with main query in cakephp 3. As I see this link , that is good to understand. 我想在cakephp 3中将子查询与主查询一起使用。如我所见, 此链接很容易理解。 But I want to use subquery in mysql FROM clause.
但是我想在mysql FROM子句中使用子查询。 ie, "SELECT * FROM (SELECT * FROM table_name)".
即“ SELECT * FROM(SELECT * FROM table_name)”。 But I can't get any idea about syntax for it.
但是我对它的语法一无所知。 If anyone have ever tried this in cakephp 3, then answer will be appreciated.
如果有人曾经在cakephp 3中尝试过,那么答案将不胜感激。 Here are some code which I have tried but did't worked for me.
这是一些我尝试过但对我不起作用的代码。
$purchases = TableRegistry::get('Purchases');
$sublastitem = $purchases->find()
->select([
'id',
'customer_id',
'item'
])
->where(function ($exp, $q) use($custids)
{
return $exp->in('customer_id', ['1','2']);
})
->order(['id' => 'DESC']);
Above is the subquery which I want to use in FROM clause. 上面是我要在FROM子句中使用的子查询。
And these code I have tried (commented lines are tried. Others are as it is for all try). 我尝试了这些代码(尝试了注释行。其他都按原样进行)。
// $lastitem = $sublastitem->find();
// $lastitem = $purchases->find($sublastitem);
// $lastitem = $purchases->all($sublastitem);
$lastitem->select([
'id',
]);
$lastitem->group('customer_id');
I found a link which describes my question more clearly. 我找到一个链接,可以更清楚地描述我的问题。 But answer in this link is not acceptable for me as I want to execute ORDER BY before GROUP BY.
但是此链接中的答案对我来说不可接受,因为我想在GROUP BY之前执行ORDER BY。 Here is link
这是链接
Here is query which I want in Cakephp 3. 这是我想要在Cakephp 3中查询。
SELECT * FROM (SELECT 'id', 'customer_id', 'item' FROM purchases WHERE customer_id IN (1, 2) ORDER BY id) t GROUP BY customer_id
You will have to create two separate query objects. 您将必须创建两个单独的查询对象。 That means that you will have to use a syntax similar to this:
这意味着您将必须使用类似于以下的语法:
$matchingUsers = $users->find('all')->select('id');
$matchingPaurchases = $purchases->find('all')->where(['user_id' => $matchingUsers]);
This will create something like this: SELECT purchase_id, purchase_price, purchase_item_id FROM purchases WHERE user_id IN(1,2,3,4,5)
这将创建类似以下内容的内容:
SELECT purchase_id, purchase_price, purchase_item_id FROM purchases WHERE user_id IN(1,2,3,4,5)
See SubQueries in the CookBook 请参阅CookBook中的子查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.