converting mysql query to redbean query - redbean

Can anyone help me convert this mysql query to redbean query please?
SELECT category,sum(price) from transaction GROUP BY category.

We can use like
$results = R::getAll( 'SELECT category,sum(price) from transaction GROUP BY category' );
// $results is multidimensional array
Here is reference link: http://www.redbeanphp.com/queries

You don't need to convert anything. You just write:
$transactions = R::get("SELECT category,sum(price) from transaction GROUP BY category");

A better conversion would be:
$sql = "SELECT category, sum(price) FROM transaction GROUP BY category";
$transactions = R::getAll($sql);

Related

Rails Translate SQL raw in ActiveRecord

I have this SQL query
sql = "select mt1.* from mail_templates as mt1 join mail_templates as mt2 where mt1.template_id = mt2.id AND mt1.technical_name='#{name}' AND mt2.festival_id=#{festival}"
If I execute this query with ActiveRecord::Base.connection.execute(sql).first it returns an array and I need to have a MailTemplate ActiveRecord.
I don't know how to do it.
Thanx for your help
I found the solution by using
sql = "select mt1.* from mail_templates as mt1 join mail_templates as mt2 where mt1.template_id = mt2.id AND mt1.technical_name='#{name}' AND mt2.festival_id=#{festival}"
MailTemplate.find_by_sql(sql)

COUNT and GROUP BY using Zend Framework 2 and tableGateway

In Zend Framework 2, using tableGateway, I want to run the following SQL query:
SELECT categories.category_name, COUNT(forums.forum_id)
FROM categories LEFT JOIN forums
ON categories.category_id = forums.category_id
GROUP BY categories.category_name;
Problem is that I simply don't know how to do it. I know how to use $select->join() for example, but I can't figure out how to also do a COUNT and GROUP BY.
What I want with my SQL: I have 2 tables; categories and forums. I want to select all the categories from categories and for each category I want the amount of forums.
Someone on another forum gave me the correct answer, and this works for me. Thought I would share it in case anyone else is having a similar question. Here is how I have it now:
use Zend\Db\Sql\Expression;
$resultSet = $this->tableGateway->select(function (Select $select)
{
// Select columns and count the forums.
$select->columns(array(
'category_name',
'forumsCount' => new Expression('COUNT(forums.forum_id)')
));
// Left-join with the forums table.
$select->join('forums', 'categories.category_id = forums.category_id', array(), 'left');
// Group by the category name.
$select->group('categories.category_name');
});
return $resultSet;
Your query looks right. Does it work as expected when you run it directly on the database.
I think you might just need to execute the raw query using an adapter.
$sql = "SELECT categories.category_name, COUNT(forums.forum_id) FROM categories LEFT JOIN forums ON categories.category_id = forums.category_id GROUP BY categories.category_name";
$statement = $this->adapter->query($sql);
return $statement->execute();

Nested Select with ZF2

Trying to get a nested select using Zend\Db\Sql\Select and can't see anything at all in the documentation or on google.
Wanting to do something like this:
SELECT
table1.*,
(SELECT x,y,z FROM table2 WHERE table2.a = table1.a) as b
FROM table1
Without the nested select, it would look something like this:
$select = new Zend\Db\Sql\Select;
$select
->columns(array(
'*'
))
->from('table1')
ZF1 looked about creating a subSelect item and then adding it as an Expression inside the list of columns but in ZF2 it complains about an Expression needing to be a string.
Edit: The nested-select needs to be as a column as I end up with multiplied rows when using GROUP BY on same column name. This is the correct query I'm trying to get into Zend\Db\Sql\Select:
SELECT
users.id,
(SELECT count(explorations.id) FROM explorations WHERE user_id = users.id) as total_explorations,
count(villages.id)
FROM
users
INNER JOIN
villages
on (villages.user_id = users.id)
GROUP BY
users.id
Ralph Schindler has a repository of different DB patterns that he has specifically implemented in Zend\Db. Here's one for subselects: https://github.com/ralphschindler/Zend_Db-Examples/blob/master/example-20.php
The content is this:
<?php
/** #var $adapter Zend\Db\Adapter\Adapter */
$adapter = include ((file_exists('bootstrap.php')) ? 'bootstrap.php' : 'bootstrap.dist.php');
refresh_data($adapter);
use Zend\Db\Sql;
use Zend\Db\ResultSet\ResultSet;
$sql = new Sql\Sql($adapter);
$subselect = $sql->select();
$subselect->from('artist')
->columns(array('name'))
->join('album', 'artist.id = album.artist_id', array())
->where->greaterThan('release_date', '2005-01-01');
$select = $sql->select();
$select->from('artist')
->order(array('name' => Sql\Select::ORDER_ASCENDING))
->where
->like('name', 'L%')
->AND->in('name', $subselect);
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$rows = array_values(iterator_to_array($result));
assert_example_works(
count($rows) == 2
&& $rows[0]['name'] == 'Lady Gaga'
&& $rows[1]['name'] == 'Linkin Park'
);
Basically, you can use one select as the value of the predicate of another select.
I would suggest you restructure you SQL query. I'm not sure which database you are using, but if you are using MySQL, the COUNT function can use the DISTINCT keyword. This way you don't count the duplicated ids. I've adjusted your SQL query to what I would use, this way you eliminate the need for inner select.
SELECT
users.id,
COUNT(DISTINCT explorations.id) AS total_explorations,
COUNT(DISTINCT villages.id) AS total_villages
FROM users
INNER JOIN villages ON villages.user_id = users.id
INNER JOIN explorations ON explorations.user_id = users.id
GROUP BY users.id
I haven't run this query, but I'm sure it should work and give you the result you want. Hopefully I'm not misunderstanding your situation. Below is the equivalent Zend Framework 2 select.
$select = $sql->select('users');
$select->columns(array('id'));
$select->join('villages',
'villages.user_id = users.id',
array(
'total_villages' => new Expression("COUNT(DISTINCT villages.id)")
)
);
$select->join('explorations',
'explorations.user_id = users.id',
array(
'total_explorations' => new Expression("COUNT(DISTINCT explorations.id)")
)
);
What you are describing is defined as a JOIN. There are some different join scenarios and i will not cover the differences of them, but the most commons would be INNER JOIN or LEFT JOIN.
And this is indeed to be found inside the ZF2-Documentation of Zend\Db\Sql#Join
The Query would look like this:
Select
t1.*,
t2.field1,
t2.field2,
t2.field3
FROM
tablename1 t1,
tablename2 t2
WHERE
t1.field = t2.field
Looking at the Documentation of ZF2-Documentation of Zend\Db\Sql#Join, i think the Select would look like this:
$select = new \Zend\Db\Sql\Select();
$select->columns(array(
'id',
'title',
// List ALL Columns from TABLE 1 - * is bad/slow!
), true)->from(array(
't1' => 'tablename1'
))->join(
'tablename2',
'id = t1.id',
array(
'username',
'email',
// List ALL Columns from TABLE 2 u want to select
),
$select::JOIN_INNER
)
Another i think: If you don't use the columns() you'd SELECT * but for your own sake, start writing good queries ;) Have more control over your code!
Can't promise that this code works, since i don't use Zend\Db on my own, but using the Documentation on the right point should get you running nonetheless.
I Hope I am getting your problem correctly...
Still not upgraded myself to ZF2 but this is one of the way you can create a nested Select statement in ZF1 if you are using MVC architecture(try it in ZF2 also).
$table1 = new table1();
$table1->select()->from('table1',array('*',
'b' => '(SELECT x,y,z FROM table2 WHERE table2.a = table1.a)',
));
Update:
Got back to this after your comment and realized that the code I've written would not work as you will not be able select multiple columns from another table into a single column(i.e x,y,z in b).
But yes it would work in case you have to perform some agg. function on the other table which gives out a single column. e.g.
$table1 = new table1();
$table1->select()->from('table1',array('*',
'b' => '(count (*) FROM table2 WHERE table2.a = table1.a)',
));
So this would work.
This way you can get some of the columns with some function performed on them.
And the rest of the columns from the other table(table2) you can get using a join.

Sybase - Get names of procs calling a given proc

I am looking for a functionality in reverse to sp_depends. sp_depends gives names of objects that the current object is using.
I want to get info in a reverse manner i.e. what all objects(procs in my case) calls the given proc ?
Note
I am using Sybase 12.5
I hope it will help you:
declare #Proc varchar(30)
select #Proc='ProcName'
select sod.name
from sysobjects so
join sysdepends sd on sd.id = so.id
join sysobjects sod on sod.id = sd.depid
where so.name = #Proc
and sod.type = 'P'
Try this query, I fixed the query of the previous answer, It gets the stored procedure(s) than call(s) the given stored procedure:
declare #Proc varchar(30)
select #Proc='procedure name'
select so.name
from sysobjects so
join sysdepends sd on sd.id = so.id
join sysobjects sod on sod.id = sd.depid
where sod.name = #Proc
and sod.type = 'P';

How to do a "Select count..." with symfony and propel?

I'm trying to do a very simple sql query like this, to a propel Criteria :
SELECT count(id_user) FROM myTable WHERE id_page = 5
I did'nt found informations on the documentation.
Have you an idea ??
$c = new Criteria();
$c->add(myTablePeer::ID_PAGE,5);
$count = myTablePeer::doCount($c);
If you want to issue a SELECT COUNT(*) based on your current ModelCriteria you can also perform
$yourCriteria->count();
This will return you the number of results.

Resources