adding values from a group by - mysql

SELECT created_time, SUM(score) FROM traineescoretest Group By created_time
Here's my sql query and I'd like to know how to convert it to codeigniter syntax. Ive been searching on it since yesterday but found no luck so far.

Try this, Reference
$this->db->select('created_time, SUM(score) as total_score');
$this->db->from('traineescoretest');
$this->db->group_by('created_time');
$query = $this->db->get();
return $query->result();

You can try like this:
$this->db->select($field, false);
$this->db->from($this->main_table);
if ($extracond != "") {
$this->db->where($extracond);
}
if ($group_by != "") {
$this->db->group_by($group_by);
}
$list_data = $this->db->get()->result();
$field = "created_time, SUM(score)";
$group_by = "created_time";
All In one function to fire a query.

Related

How to convert sql query to codeigniter query

Can somebody help me convert this Sql Query
SELECT *
FROM customer c
LEFT JOIN customer_order co
ON c.customer_number = co.customer_number
AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid'
AND c.order_status = 'unserve'
AND co.cus_ord_no IS null
into Codeigniter query just like the image below for example
When query statements do not have clauses that need to change conditionally then using $this->db-query() is the way to go.
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co
ON c.customer_number=co.customer_number AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid' AND c.order_status='unserve' AND co.cus_ord_no IS null";
$query = $this->db->query($sql)->result();
echo json_encode($query);
It might be wise to include a check on the return from query() though because if it fails (returns false) then the call to result() will throw an exception. One way that can be handled is like this.
$query = $this->db->query($sql);
if($query !== FALSE)
{
echo json_encode($query->result());
return;
}
echo json_encode([]); // respond with an empty array
Query Builder (QB) is a nice tool, but it is often overkill. It adds a lot of overhead to create a string that literally is passed to $db->query(). If you know the string and it doesn't need to be restructured for some reason you don't need QB.
QB is most useful when you want to make changes to your query statement conditionally. Sorting might be one possible case.
if($order === 'desc'){
$this->db->order_by('somefield','DESC');
} else {
$this->db->order_by('somefield','ASC');
}
$results = $this->db
->where('other_field', "Foo")
->get('some_table')
->result();
So if the value of $order is 'desc' the query statement would be
SELECT * FROM some_table WHERE other_field = 'Foo' ORDER BY somefield 'DESC'
But if you insist on using Query Builder I believe this your answer
$query = $this->db
->join('customer_order co', "c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared')", 'left')
->where('c.customer_status','unpaid')
->where('c.order_status','unserve')
->where('co.cus_ord_no IS NULL')
->get('customer c');
//another variation on how to check that the query worked
$result = $query ? $query->result() : [];
echo json_encode($result);
You can do
public function view_customers()
{
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co ON c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared') WHERE c.customer_status='unpaid' AND c.order_status = 'unserve' AND co.cus_ord_no IS null";
return $this->db->query($sql)->result();
}
You can use row() for one output to object, or row_array() if one output but array. result() is multiple objects and result_array() is multiple arrays.
My way do usually is like this:
Controller:
public function view()
{
$this->load->model('My_Model');
$data = new stdclass;
$data->user_lists = $this->my_model->view_users(array('nationality'=>'AMERICAN'));
}
Model:
public function view_users($param = null) //no value passed
{
$condition = '1';
if (!empty($param)) { //Having this will trap if you input an array or not
foreach ($param as $key=>$val) {
$condition .= " AND {$key}='{$val}'"; //Use double quote so the data $key and $val will be read.
}
}
$sql = "SELECT * FROM users WHERE {$condition}"; //Use double quote so the data $condition will be read.
// Final out is this "SELECT * FROM users WHERE 1 AND nationality='AMERICAN'";
return $this->db->query($sql)->result();
}

Codeigniter active record COUNT return null

I need to select some data from a table and count related images from another table.
The code I'm using is the following ( from model file)
$this->rci_db->select ("
$this->tbl_register.id,
$this->tbl_register.cor,
DATE_FORMAT($this->tbl_register.registerdate, '%d/%m/%Y') AS registerdate,
$this->tbl_registrations.registration,
$this->tbl_aircrafts.cn,
$this->tbl_aircrafts.built,
$this->tbl_manufacturers.manufacturer,
$this->tbl_models.type AS model,
COUNT($this->tbl_images.imgid) AS count
");
$this->rci_db->from("$this->tbl_register");
$this->rci_db->join("$this->tbl_registrations", "$this->tbl_registrations.rid = $this->tbl_register.rid", 'left');
$this->rci_db->join("$this->tbl_aircrafts", "$this->tbl_register.aid = $this->tbl_aircrafts.aid", 'left');
$this->rci_db->join("$this->tbl_manufacturers", "$this->tbl_manufacturers.mid = $this->tbl_aircrafts.mid", 'left');
$this->rci_db->join("$this->tbl_models", "$this->tbl_models.tid = $this->tbl_aircrafts.tid", 'left');
$this->rci_db->join("$this->tbl_images", "$this->tbl_register.id = $this->tbl_images.id", 'left');
$this->rci_db->where("$this->tbl_register.rid", $rid);
$query = $this->rci_db->get();
if ($query->num_rows() > 0)
{
return $query->result();
}
return false;
The query return null for the COUNT statement and I'm not able to figure out what's wrong.
Other data are returned correctly
Thanks for any help.
That count is in another table, so you must relate those somehow in your query. Instead of joining in this case it might be easy to just use a sub select.
Something like this in your select:
$this->rci_db->select ("
$this->tbl_register.id,
$this->tbl_register.cor,
DATE_FORMAT($this->tbl_register.registerdate, '%d/%m/%Y') AS registerdate,
$this->tbl_registrations.registration,
$this->tbl_aircrafts.cn,
$this->tbl_aircrafts.built,
$this->tbl_manufacturers.manufacturer,
$this->tbl_models.type AS model,
(SELECT COUNT($this->tbl_images.imgid) FROM $this->tbl_images WHERE $this->tbl_register.id = $this->tbl_images.id) AS count
");

October cms - Eloquent - Issues in creating model query from sql query

I have a sql query that is working ok
SELECT
*
FROM
jml_gkb_eventos
WHERE
id IN (SELECT
evento_id
FROM
jml_gkb_etiqueta_evento
WHERE
etiqueta_id IN (SELECT
id
FROM
jml_gkb_etiquetas
WHERE
etiqueta REGEXP ? ) group by evento_id having count(evento_id) = ?);
But i can't figure out how convert this sql query to Eloquent model query. I know that i'm near solution (related with this problem here) and tried some variations of the following code:
$pesquisa = preg_split('/\s+/', $temp, -1, PREG_SPLIT_NO_EMPTY);
$cadeiapesquisa = implode('|', $pesquisa);
$contagem = count($pesquisa);
if (Session::get('modo') == 0){
if ( strlen($cadeiapesquisa) > 0 ){
$this['records'] = Evento::with('etiquetas')->whereHas('etiquetas', function($query) use ($cadeiapesquisa, $contagem){
$query->where('etiqueta', 'regexp', "$cadeiapesquisa")->groupBy('evento_id')->having('COUNT(evento_id) = '.$contagem);
})->orderBy('id', 'DESC')->paginate(25);
} else {
$this['records'] =Evento::paginate(25);
}
}
I get it working without the ->having() part in inner query, obviosly without the expected return, but without errors.
What i'm doing wrong ?
TIA
JL
[EDIT] - With the code above i get the following error:
I found the problem. It is with the 'count()' part not being processed by eloquent. Placing the count on DB::raw is working as expected at least with the tests i've done. The whole snipet of code with some adjustements is:
$pesquisa = preg_split('/\s+/', $temp, -1, PREG_SPLIT_NO_EMPTY);
$cadeiapesquisa = implode('|', $pesquisa);
$contagem = count($pesquisa);
if (Session::get('modo') == 0){
if ( strlen($cadeiapesquisa) > 0 ){
$this['records'] = Evento::with('etiquetas')->whereHas('etiquetas', function($query) use ($cadeiapesquisa, $contagem){
$query->where('etiqueta', 'regexp', "$cadeiapesquisa")->groupBy('evento_id')->having(DB::raw("COUNT('etiqueta_id')"), '>=', $contagem );
})->paginate(25);
} else {
$this['records'] = Evento::paginate(25);
}
}
JL

Mysql PDO (Getting total from all colums) [duplicate]

I'm new to php and I've searched for the past hour and read all the documentation I could find and nothing is helping. I have a table that has a bunch of rows of data. I'm trying to pick one column from the whole table and add them all together. Here is what I got. All this tells me is how many rows there are that match my query, not the total sum of column I want. Any help is appreciated.
$res1 = $db->prepare('SELECT sum(distance) FROM trip_logs WHERE user_id = '. $user_id .' AND status = "2"');
$res1->execute();
$sum_miles = 0;
while($row1 = $res1->fetch(PDO::FETCH_ASSOC)) {
$sum_miles += $row1['distance'];
}
echo $sum_miles;
You're only returning one row in this instance. Modify your summed column to have an alias:
SELECT SUM(distance) AS totDistance FROM trip_logs ....
Now you can can fetch the row -
$row = $res1->fetch(PDO::FETCH_ASSOC);
echo $row['totDistance'];
No need to loop.
You can use SUM() without explicitely grouping your rows because if you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.
If however you want to use the SUM() function for something slightly more complicated you have to group your rows so that the sum can operate on what you want.
If you want to get multiple sums in a single statement, for example to get the distance for all users at once, you need to group the rows explicitely:
$res1 = $db->prepare("
SELECT
SUM(distance) AS distance,
user_id
FROM trip_logs WHERE status = '2'
GROUP BY user_id
");
$res1->execute();
while ($row = $res1->fetch(PDO::FETCH_ASSOC))
{
echo "user $row[user_id] has runned $row[distance] km.\n";
}
This will return the sum of distances by user, not for all users at once.
Try this if you are using a Class :
class Sample_class{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function GetDistant($user_id,$status) {
$query = $this->db->prepare("SELECT sum(distance) FROM trip_logs WHERE user_id =? AND status =?");
$query->bindValue(1, $user_id);
$query->bindValue(2, $status);
try{ $query->execute();
$rows = $query->fetch();
return $rows[0];
} catch (PDOException $e){die($e->getMessage());}
}
}
$dist = new Sample_class($db);
$user_id = 10;
$status = 2;
echo $dist->GetDistant($user_id,$status);

order and limit on a select query zend framework 2

Earlier this day a asked a question about an update query. But now i want to select some things ( and it is working ) but I also want to order them and put a limit on it.
This is the code to select all the food :
public function getFood($id)
{
$id = (int)$id;
$rowset = $this->tableGateway->select(array('kindOfFood_id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
But how can i do this :
Select * from KindOfFood ==> order by kindOfFood_votes DESC ?
I saw on the documentation you can do something like this, but it doesn't work with me?
$rowset = $artistTable->select(function (Select $select) {
$select->where->like('name', 'Brit%');
$select->order('name ASC')->limit(2);
});
Are you looking to return only single row or multiple rows.
Try this for multiple rows -
use Zend\Db\Sql\Select; //at the top of the page among other use statements.
public function getFood($id)
{
$id = (int) $id;
$select = new Select(TABLE_NAME); //CHANGE TABLE_NAME as per needs
$select->where('kindOfFood_id = ' . $id);
$select->order('kindOfFood_votes DESC');
$resultSet = $this->tableGateway->selectWith($select); //Will get array of rows.
//$row = $rowset->current(); THIS IS FOR RETURNING ONLY SINGLE ROW NOT ALL ROWS
if (!$resultSet) {
throw new \Exception("Could not find rows with food id - $id");
}
return $resultSet;
}
Can access the returned resultSet via loop. Eg: foreach
foreach($resultSet as $row) {
echo $row->kindOfFood_id; //or something
}
Note:
If you need only
Select * from KindOfFood order by kindOfFood_votes DESC
then remove the $select->where('kindOfFood_id = ' . $id); line from above.