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

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.

Related

trying to convert sql to linq sql

I'm trying to convert this SQL code to linq sql. But I don't understand even with the doc... someone can help me please ?
select prcleunique, LibelleProjet, from projet a
where eqcleunique in (select EqCleunique from Compo where uscleunique = '{0}')
and (a.socleunique in (select socleunique from utilisat where uscleunique = '{0}') or a.socleunique is null)
and a.archive = 2 order by LibelleProjet", idUtilisateur);
Those nested sql queries can be broken down nicely in Linq. Every time you have a select have a seperate linq query:
var clause1 = from row in _db.Compo where uscleunique == '{0}' select EqCleunique;
Then use the clauses in the last query
var result = from row in _db.project where clause1.Contains(row.eqcleunique) select row.whatever;
I hope this example is enough to get you started.

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();

Rails + Postgres: How to select count of how many records are updated or inserted?

So I have an update statement:
UPDATE billing_infos set card_number = ''
FROM orders
WHERE billing_infos.order_id = orders.id ...);`
How would I find the count of how many records are updated by this statement?
I'm doing this in my console through ActiveRecord::Base.connection.execute() so it's just returning a <PG::Result:0x007f9c99ef0370> object.
Anyone know how I could do this using SQL or a Rails method?
p = ActiveRecord::Base.connection.execute(<query>)
p.cmd_status
This gives the command status. Something like
UPDATE 16
For more methods on PG::Result, refer here
While solution showed by Vimsha will definitely work, there is also another solution (assuming you use recent enough pg), which could be a bit nicer:
with u as (
update ... returning 1
)
select count(*) from u;
That's one query, and it's technically a select, so you run it as any other select.
As mentioned in a comment of another answer, the easiest way is to use the cmd_tuples attribute of the result
result = ActiveRecord::Base.connection.execute("insert into tbl select 'test' col")
puts result.cmd_tuples
result
1

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.

converting mysql query to redbean query

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);

Resources