I'm working on a school project and I'm trying to get a query working.
SELECT *
FROM `ziekmeldingen` AS a
WHERE NOT EXISTS
(SELECT *
FROM `ziekmeldingen` AS b
WHERE `ziek` = 1
AND a.personell_id = b.personell_id)
Name of the model: ZiekmeldingenModel
I tried 2 things, both dont work ->
$medewerkers = ZiekmeldingenModel::whereNotExists(function($query)
{
$query->select()->from('ziekmeldingen AS b')->where('ziek', '=', '1')->where('ziekmeldingen.personell_id', '=', 'b.personell_id');
})->get();
return $medewerkers;
And
$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->get();
Both of them give back all the results from the table while it should only give back 1 result (I've tested the original query, it works).
EDIT: Forgot to mention I'm using relationships in the model. So the raw solution probably won't work anyway
Found the answer. Had to use a combo of both the things I tried.
$medewerkers = ZiekmeldingenModel::select()
->from(DB::raw('`ziekmeldingen` AS a'))
->whereNotExists(function($query){
$query->select()
->from(DB::raw('`ziekmeldingen` AS b'))
->whereRaw('`ziek` = 1 AND a.personell_id = b.personell_id');
})->get();
return $medewerkers;
Thanks for any help and effort.
Definitely no need for select(). Also no raw in from or whereRaw needed.
The only unusual thing here is raw piece in the where, since you don't want table.field to be bound and treated as string. Also, you can use whereRaw for the whole clause in case you have your tables prefixed, otherwise you would end up with something like DB_PREFIX_a.personell_id, so obviously wrong.
This is how you do it:
$medewerkers = ZiekmeldingenModel::from('ziekmeldingen AS a')
->whereNotExists(function ($q) {
$q->from('ziekmeldingen AS b')
->where('ziek', 1)
->where('a.personell_id', DB::raw('b.personell_id'))
// or:
// ->whereRaw('a.personell_id = b.personell_id');
})->get();
Use the take() method though if you're not ordering your results the record you get back could be any of the results.
$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->take(1)->get();
Related
I want to union two tables with where clause in zf2:-
table1 app_followers
table2 app_users
where condition could be anything
and order by updated_date.
Please let me know the query for zend 2.
Thanks..
Using UNION is ZF2:
Using ZF2 dedicated class Combine Zend\Db\Sql\Combine
new Combine(
[
$select1,
$select2,
$select3,
...
]
)
A detailed example which uses combine is as follows:
$select1 = $sql->select('java');
$select2 = $sql->select('dotnet');
$select1->combine($select2);
$select3 = $sql->select('android');
$selectall3 = $sql->select();
$selectall3->from(array('sel1and2' => $select1));
$selectall3->combine($select3);
$select4 = $sql->select('network');
$selectall4 = $sql->select();
$selectall4->from(array('sel1and2and3' => $selectall3));
$selectall4->combine($select4);
$select5 = $sql->select('dmining');
$selectall5 = $sql->select();
$selectall5->from(array('sel1and2and3and4' => $selectall4));
$selectall5->combine($select5);
which is equivalent to the normal SQL query for UNION:
SELECT * FROM java
UNION SELECT * from dotnet
UNION SELECT * from android
UNION SELECT * from network;
UNION SELECT * from dmining;
I hope it helps.
I wanted to do a similar task and spent a lot of time while to figure out how to do that in the right way.
The idea with Laminas\Db\Sql\Combine is really well but you cannot apply the ordering to this object and as the result, it's useless in this case.
Finally, I ended up with the next code:
$skill = $sql->select('skill');
$language = $sql->select('language');
$location = $sql->select('location');
$occupation = $sql->select('occupation');
$skill->combine($language);
$language->combine($location);
$location->combine($occupation);
$combined = (new Laminas\Db\Sql\Select())
->from(['sub' => $skill])
->order(['updated_date ASC']);
However, it's a bit messy with parentheses. If it's a matter for you, please check this comment on Github, but on MySQL id doesn't matter, not sure about other databases.
I need to write this query with Doctrine. How can I write it down using QueryBuilder?
SELECT charges.id, charges.currency, charges.total_transactions,
charges.total_volume, charges.commission, refunds.total_payouts
FROM
(SELECT ...very long query...) charges
LEFT JOIN
(SELECT ...very long query...) refunds
ON charges.id = refunds.id AND charges.currency = refunds.currency
You can use Native SQL and map results to entities:
use Doctrine\ORM\Query\ResultSetMapping;
$rsm = new ResultSetMapping;
$rsm->addEntityResult('AppBundle:Charges', 'charges')
->addEntityResult('AppBundle:Refunds', 'refunds')
->addFieldResult('charges', 'id', 'id')
->addFieldResult('charges', 'currency', 'currency')
->addFieldResult('charges', 'total_transactions', 'total_transactions')
->addFieldResult('charges', 'total_volume', 'total_volume')
->addFieldResult('charges', 'commission', 'commission')
->addFieldResult('refunds', 'total_payouts', 'total_payouts')
;
$sql = "
SELECT
charges.id,
charges.currency,
charges.total_transactions,
charges.total_volume,
charges.commission,
refunds.total_payouts
FROM
(SELECT ...very long query...) charges
LEFT JOIN
(SELECT ...very long query...) refunds ON charges.id = refunds.id AND charges.currency = refunds.currency
WHERE some_field = ?
";
$query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
$query->setParameter(1, $name);
$entities = $query->getResult();
You can use DQL like this:
$dql = "SELECT ...";
$q = $entityManager->createQuery($dql)->setParameters($arrayParameters);
$result = $q->execute();
or QueryBuilder for each sub-query, like:
// subquery 1
$subQuery1 = $entityManager->createQueryBuilder()
->select('...')
->from('...')
->getDQL()
;
// subquery 2
$subQuery2 = ...
// etc
// ...
// main query
$query = $entityManager->createQueryBuilder()
->select('...')
->from('...', $subQuery1)
->leftJoin('...', $subQuery1->getDQL()),
->where()
;
PS: I just try provide gist for you... hope now you have clue...
Now I found out that it's impossible.
Comment created by stof:
DQL is about querying objects. Supporting subselects in the FROM clause means that the DQL parser is not able to build the result set mapping anymore (as the fields returned by the subquery may not match the object anymore).
This is why it cannot be supported (supporting it only for the case you run the query without the hydration is a no-go IMO as it would mean that the query parsing needs to be dependant of the execution mode).
In your case, the best solution is probably to run a SQL query instead (as you are getting a scalar, you don't need the ORM hydration anyway)
Source: https://github.com/doctrine/doctrine2/issues/3542
I have a simple Person tree with parent_id.
I wont to build a (Yii2) query to find all children of a given Person, that are parent of someone else (a.k.a not leaves).
The output SQL should looks like this:
select * from person t
where exists (select 1 from person p2 where t.id = p2.parent_id);
But cant find the right way to build this with the query builder, there is a method ->exists(), but not much documentation/examples about it.
Not sure if i understood correctly, but do you look something like this.
$subQuery = (new \yii\db\Query)
->select([new \yii\db\Expression('1')])
->from('person p2')
->where('t.id = p2.parent_id');
$query = (new \yii\db\Query())
->select('*')
->from('person t')
->where(['exists', $subQuery]);
$command = $query->createCommand();
print_r ($command->sql);
Generates sql like:
SELECT * FROM `person` `t` WHERE EXISTS (SELECT 1 FROM `person` `p2` WHERE t.id = p2.parent_id)
You should try something like :
$tableName = Person::tableName();
$subQuery = (new Query())->select('*')->from($tableName . ' t2')->where('t1.id=t2.parent_id');
$persons = Person::find()->from($tableName . ' t1')->where(['exists', $subQuery])->all();
http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#where
I don't know the right way with only queries, but if you use PHP also, then I think this will help you.
And also try to search in Google with keywords: hierarchical menu PHP
When I try the follow mysql query in send I just get back an empty results set (who suposed to be filled).
I tried the follow query in my mysql workbench (gives a results back)
SELECT `websites`.*, `s`.`website_id` AS `websites.id`
FROM `websites`
INNER JOIN `websites_statistics` AS `s` ON `s`.`website_id` = `websites`.`id`
WHERE `websites`.`website` = 'google.com' LIMIT 0,1
And this one in my ZF2 application (empty result set)
$sql = new Sql($this->tableGateway->getAdapter());
$select = $sql->select();
$select->from('websites')
->join(array('s' => 'websites_statistics'), 's.website_id = websites.id', array('websites.id' => 'website_id'), \Zend\Db\Sql\Select::JOIN_INNER)
->where(array('websites.website' => 'google.com'));
$resultSet = $this->tableGateway->selectWith($select);
echo $select->getSqlString();
return $resultSet;
Debug result:
SELECT "websites".*,
"s"."website_id" AS "websites.id"
FROM "websites"
INNER JOIN "websites_statistics" AS "s" ON "s"."website_id" = "websites"."id"
WHERE "websites"."website" = 'google.com'
(!updated) The query a bit so it's more easier. I think there goes something wrong at the first moment because I think "s"."website_id" AS "websites.id" has to flip in the other direction .. "websites.id" AS "s"."website_id" I need websites.id to take record by website_id from the websites_statistics table.
Thanks in advance!
Nick
I got it work. The problem wasn't the query it's self. I had to add the fields of the second table (to one I join) to the model (exchangeArray) of the first table! That did the trick. Thanks you all.
I just want somthing like this:
select SUM(*) from `mytable` group by `year`
any suggestion?
(I am using Zend Framework; if you have a suggestion using ZF rather than pure query would be great!)
Update: I have a mass of columns in table and i do not want to write their name down one by one.
No Idea??
SELECT SUM(column1) + SUM(column2) + SUM(columnN)
FROM mytable
GROUP BY year
Using the Zend Framework's Zend_Db_Select, your query might look like
$db = Zend_Db::factory( ...options... );
$select = $db->select()
->from('mytable', array('sum1' => 'SUM(`col1`)', 'sum2' => 'SUM(col2)')
->group('year');
$stmt = $select->query();
$result = $stmt->fetchAll();
Refer to the Zend_Db_Select documentation in the ZF manual for more.
EDIT: My bad, I think I misunderstood your question. The query above will return each colum summed, but not the sum of all of the columns. Rewriting Maxem's query so that you can use it with a Zend Framework DB adapter, it might look like
$sql = '<insert Maxem's query here>';
$result = $db->fetchAll($sql);
You might choose to use fetchCol() to retrieve the single result.
It sounds like you don't want to explicitly enumerate the columnn and that you want to sum all the columns (probably excluding the year column) over all the rows, with grouping by year.
Note that the method Zend_Db_Table::info(Zend_Db_Table_Abstract::COLS) will return an array containing the columns names for the underlying table. You could build your query using that array, something like the following:
Zend_Db_Table::setDefaultAdapter($db);
$table = new Zend_Db_Table('mytable');
$fields = $table->info(Zend_Db_Table_Abstract::COLS);
unset($fields['year']);
$select = $table->select();
$cols = array();
foreach ($fields as $field){
$cols[] = sprintf('SUM(%s)', $field);
}
$select->cols(implode(' + ', $cols));
$select->group('year');
I have not tested the specific syntax, but the core of the idea is the call to info() to get the fields dynamically.
Done in ZF rather than pure query and you don't have to write the name of the columns one by one.
(I assume you are extending Zend_Db_Table_Abstract)
If you're asking how to write
select SUM(*) from `mytable` group by `year`
This is how it is done:
public function sumOfAllFields(){
return $this->fetchAll( $this->select()->from('mytable','SUM(*)')->group('year') )->toArray();
}
Or not using Zend...
function mysql_cols($table){
$sql="SHOW COLUMNS FROM `".$table."`";
$res=mysql_query($sql);
$cols=array();
while($row=mysql_fetch_assoc($res))$cols[]=$row['Field'];
return $cols;
}
$cols=mysql_cols("mytable");
$select_sql=array();
foreach($cols as $col){
$select_sql[]="SUM(`".$col."`)";
}
$select_sql=implode('+',$select_sql);
$sql="select (".$select_sql.") from `mytable` group by `year`";