cakephp group by with n result for each group - php

I need to extract 3 result from each category in a database using cakephp, I tried to query in database using mysql session variable and conditions as below
SELECT *, #question_cat_rank := 0, #question_cat_country:=''
FROM
(SELECT *,
#question_cat_rank := IF(#question_cat_country = question_setname.question_cat, #question_cat_rank + 1, 1) AS question_cat_rank,
#question_cat_country := question_cat
FROM question_setname
ORDER BY question_cat desc
) ranked
WHERE question_cat_rank <= 3
its working fine in mysql query analyzer but when i query using cakephp its returning all results in table instaed of 3 results
i tried to create it using cakephp way like below
public $virtualFields = array(
'#catvirt' => 1,
'#catvirt2' => 'question_cat',
'incrmt' => 'IF(#catvirt2 = question_cat, #catvirt+1, 1)',
);
function getquestionGroup(){
$result1 = $this->find('all', array(
'fields' => array('question_cat', '#catvirt2', 'incrmt'),
'#catvirt2'=> 'question_cat',
'#catvirt' => '#catvirt'
)
);
$result = $this->find('all', array($result1,
'conditions' => array('#catvirt <=' => 3),
)
);
i tried to execute as prepared statementand stored procedure also still no luck its returning all results
any help will be appreciated

I would write that query this way:
SELECT x.*
FROM
( SELECT *
, #question_cat_rank := IF(#question_cat_country = question_cat, #question_cat_rank + 1, 1) question_cat_rank
, #question_cat_country := question_cat
FROM question_setname
, (SELECT #question_cat_rank := 0, #question_cat_country:='') vars
ORDER
BY question_cat DESC
) x
WHERE question_cat_rank <= 3;

Related

How to access a particular value from mysql database using php?

This is my php script that selects everything from invoiceNo where invoiceNo is distinct.
<?php
require 'init.php';
$query = 'SELECT * FROM `selected_items` WHERE invoiceNo IN ( SELECT DISTINCT ( invoiceNo) AS invoiceNo FROM selected_items ) GROUP BY invoiceNo;';
$res = mysqli_query($con, $query);
$result = [];
while ($row = mysqli_fetch_array($res)) {
array_push($result, [
'custInfo' => $row[0],
'invoiceNo' => $row[1],
'barcode' => $row[2],
'description' => $row[3],
'weight' => $row[4],
'rate' => $row[5],
'makingAmt' => $row[6],
'net_rate' => $row[7],
'itemTotal' => $row[8],
'vat' => $row[9],
'sum_total' => $row[10],
'bill_type' => $row[11],
'date' => $row[12],
'advance' => $row[13],
'balance' => $row[14],
]);
}
echo json_encode(['result' => $result]);
mysqli_close($con);
Right now this script gives me the first value from sum_total i.e it gives me the first row from my database how can I get the last row.I am new to programming any suggestions or help is appreciated.Thanks :)
Select * From (
SELECT t.*,
#rownum := #rownum + 1 AS rank
FROM selected_items t,
(SELECT #rownum := 0) r order by rank DESC
) si GROUP BY si.invoiceNo;
This query solved my problem
Try this, i think this is you want, may it help
$query ="SELECT max( `sum_total` ) FROM `selected_items` GROUP BY invoiceNo;";
try like this :
$query ="SELECT * FROM `selected_items` WHERE invoiceNo IN ( SELECT DISTINCT ( invoiceNo) AS invoiceNo FROM selected_items ) ORDER BY `sum_total` DESC";
$query ="SELECT max( `sum_total` ) FROM selected_items";
Where column_name can be vary.
If you need to get only last record use limit.
$query ="SELECT * FROM `selected_items` GROUP BY invoiceNo ORDER BY `sum_total` DESC limit 1;
If you need to get highest to lowest sum_total record try the below code,
$query ="SELECT * FROM `selected_items` where `sum_total` = (SELECT max( `sum_total` ) FROM `selected_items` GROUP BY invoiceNo) GROUP BY invoiceNo ORDER BY `sum_total` DESC;

using limit in get function - codeigniter

I'm using codeigniter.
Now,I would like to use limit/offset statement.
My query :
$data['all'] = $this->m_general->get('pm', array(
'user_sender' => 1,
'admin_delete' => 0
) , false);
For example :
I want using limit 0,100
You can use like below.
Replace your values with limit and offset
$data['all'] = $this->m_general->get('pm', array(
'user_sender' => 1,
'admin_delete' => 0
) , limit,offset);

How to convert a mysql query in CakePHP pagination condition

I have below MySQL query.
I just want to convert a MySQL query in CakePHP pagination condition. So that i can get result.
MySql Query:
SELECT *, 3963 * acos(cos(radians(90-lat ))*cos(radians(90-'".$result['lat']."'))".
"+sin(radians(90-lat ))* sin(radians(90-'".$result['lat']."'))".
"*cos(radians(lng- '".$result['lng']."'))) AS distance FROM member"." HAVING (distance < 5) ORDER BY distance ASC
i am using this PHP Code
$condition = array('Member.is_deleted !=' => 1, 'Member.status !=' => 0, 'OR' => array());
$this->paginate = array(
'conditions' => $condition,
'fields' => array()
);

Struggling adding WHERE clause to INNER JOIN

I have a query which is supposed to select the lowest price_per_pax_after_tax from every backend_hotels_id date_start and package_supplier and this appears to be working until I add a WHERE clause.
Here's the query:
SELECT e.price_per_pax_after_tax, e.hotel_score, e.package_id, e.package_type
FROM packages_sorted_YQU e
INNER JOIN (
SELECT db_id, MIN( price_per_pax_after_tax ) AS lowest_price, package_id, hotel_score
FROM `packages_sorted_YQU`
WHERE `package_type` IN ('9', '10', '18')
AND `package_duration` IN ('6', '8', '12')
GROUP BY
`date_start` , `package_supplier` , `backend_hotels_id`
) AS j
ON j.db_id = e.db_id
AND j.lowest_price= e.price_per_pax_after_tax
AND j.hotel_score = e.hotel_score
AND j.package_id = e.package_id;
The table is huge but all of the fields listed are INT except for date_start which is DATE
The where clause causing the problem is:
WHERE `package_type` IN ('9', '10', '18')
AND `package_duration` IN ('6', '8', '12')
Without the where clause I get over 400 results and with the where clause I get zero results :( Any help will be very much appreciated.
If your columns package_type and package_duration are of type int you don't have to wrap the values inside ' like strings.
SELECT e.price_per_pax_after_tax, e.hotel_score, e.package_id, e.package_type
FROM packages_sorted_YQU e
INNER JOIN (
SELECT db_id, MIN( price_per_pax_after_tax ) AS lowest_price, package_id, hotel_score
FROM `packages_sorted_YQU`
WHERE `package_type` IN (9, 10, 18)
AND `package_duration` IN (6, 8, 12)
GROUP BY
`date_start` , `package_supplier` , `backend_hotels_id`
) AS j
ON j.db_id = e.db_id
AND j.lowest_price= e.price_per_pax_after_tax
AND j.hotel_score = e.hotel_score
AND j.package_id = e.package_id;
The subquery:
SELECT db_id
, MIN( price_per_pax_after_tax ) AS lowest_price
, package_id
, hotel_score
FROM `packages_sorted_YQU`
WHERE `package_type` IN ('9', '10', '18')
AND `package_duration` IN ('6', '8', '12')
GROUP BY
`date_start`
, `package_supplier`
, `backend_hotels_id`
will yield indeterminate results, with or without the WHERE clause. Because you are grouping by date_start, package_supplier, backend_hotels_id and have in the SELECT list columns without any aggregate functions on them: db_id, package_id, hotel_score.
This query should work consistently if the (date_start, package_supplier, backend_hotels_id) is the Primary Key or Unique.
Which is the PRIMARY KEY of the table and are there any other UNIQUE keys?
Hi all and thank you for your valuable input. I've solved the problem without a sub-query and it works a bit faster too.
SELECT MIN
(
concat
(
LPAD(`price_per_pax_after_tax` , 5, '0'),
LPAD(`package_id` , 12, '0'),
LPAD(`hotel_score` , 7, '0')
)
) AS cat
FROM `packages_sorted_YQU`
WHERE `package_type` IN
(
9, 10, 18
)
AND `package_duration` IN
(
6, 7, 8
)
GROUP BY `date_start` , `package_supplier` , `backend_hotels_id`
Then in PHP I break apart the concatenation with:
while($r=mysql_fetch_array($q,MYSQL_ASSOC))
{
$a[lrp][] = intval(substr($r[cat], 0, 5));
$a[package_id][] = intval(substr($r[cat], 5, 12));
$a[hotel_score][] = substr($r[cat], 17, 7);
}
I was lucky that the only FLOAT value was the hotel_score so I put that last - the other two were of type INT

Cakephp using group by in find method

I'm trying to use Group by in find method for my relational database I want to get the latest record with unique receiver_id out of result set filtered by user_id and below is my code:
$this->loadModel('Chat');
$lastChat = $this->Chat->find('all', array(
'conditions' => array(
'Chat.user_id' => $user_id['User']['id']
),
'fields' => array(
'Chat.id',
'Chat.chat',
'Chat.user_id',
'Chat.receiver_id',
'Chat.read',
'Chat.created'
),
'group' => array('Chat.receiver_id'),
'order' => array('Chat.created DESC')
));
However, this does not seem to work. I'm not sure why but I'm only getting one result...
How can I get multiple results with rules based on above.
Try the following:
$db = $this->Chat->getDataSource();
$chats = $db->query("SELECT * , (Chat.user_id + Chat.receiver_id) AS dist
FROM (
SELECT *
FROM chats t
WHERE ( t.user_id =$id OR t.receiver_id =$id )
ORDER BY t.id DESC
) Chat
GROUP BY dist
ORDER BY Chat.id DESC");

Categories