SQL to Criteria using propel - symfony1

I have this sql:
SELECT link.ID, link.URL, link.ANCHOR, link.HOME, link.CREATED_AT
FROM `link`, `linkcategory`
WHERE link.ID=linkcategory.LINK_ID
GROUP BY linkcategory.LINK_ID
HAVING count(linkcategory.category_id) =(select count(*) from categoria)
And I'm trying to generate the criteria, this is the criteria that doesn't work:
$c = new Criteria();
$c->addJoin(self::ID, LinkcategoryPeer::LINK_ID);
$c->addAsColumn('catCount','(SELECT COUNT(*) FROM CATEGORIA)');
$c->addGroupByColumn(LinkcategoryPeer::LINK_ID);
$having = $c->getNewCriterion(count(LinkcategoryPeer::CATEGORY_ID),$c->getColumnForAs('catCount'));
$c->addHaving($having);
return self::doSelect($c);
The returning sql of this criteria is this one:
SELECT (SELECT COUNT(*) FROM CATEGORIA) AS catCount
FROM `link`, `linkcategory`
WHERE link.ID=linkcategory.LINK_ID
GROUP BY linkcategory.LINK_ID
HAVING 1='(SELECT COUNT(*) FROM CATEGORIA)'
I really don't know why the criteria convert the sql incorrectly. Anyone knows where is the mistake?

Try with this query. I don't remember how to perform a link.* using Propel. But I think the problem with having is that you are using the PHP count function insteand of the MySQL one.
$c = new Criteria();
$c->addSelectColumn(self::ID);
$c->addSelectColumn(self::URL);
$c->addSelectColumn(self::ANCHOR);
$c->addSelectColumn(self::HOME);
$c->addSelectColumn(self::CREATED_AT );
$c->addJoin(self::ID, LinkcategoryPeer::LINK_ID);
$c->addGroupByColumn(LinkcategoryPeer::LINK_ID);
$having = $c->getNewCriterion(
'COUNT('.LinkcategoryPeer::CATEGORY_ID.')'),
$c->getColumnForAs('catCount')
);
$c->addHaving($having);
return self::doSelect($c);

Related

select all records from left table that do not exist in right table

I am working on sql server I have two tables and I need to return records from the left table which are not found in the right table for that I am using left join like below query,
select #MID=MID,#MName=Name,#PID=PID,#PName=PName,#DID=DID from #CompanyDataInfo where id=#MCount
insert into #temp SELECT Top(1) f.Name,f.PID,f.PName,v.* FROM #CompanyDataInfo f
left join Employee v on v.Id=f.ID and v.DID=f.DID
where v.Id =#MID and v.DId = #DId and v.PId = #PId and v.CId =#CId and DATE_TIME between DATEADD(minute,-555,GETDATE()) and GETDATE() order by DATE_TIME desc
Result should be all rows from #CompanyDataInfo table while no record found in Employee table for related ID, I googled and use "v.Id is null" but not getting expected result
Is there any solution greatly appriciable
Thanks In advance
Your query is not using left join in correct way. You are using your right table reference in where clause. I try to correct it below but I don't have full information about your table schema. Please try this-
select
#MID = MID,
#MName = Name,
#PID = PID,
#PName = PName,
#DID = DID
from #CompanyDataInfo
where id = #MCount
insert into #temp
select
f.Name,
f.PID,
f.PName,
v.*
from #CompanyDataInfo f
left join Employee v on v.Id=f.ID and v.DID=f.DID
where f.Id = #MID and
f.DId = #DId and
f.PId = #PId and
f.CId = #CId and
f.DATE_TIME between DATEADD(minute,-555,GETDATE()) and GETDATE() and
v.Id is null
order by f.DATE_TIME desc
Add ...and v.Id is null to your where clause.

Query to fetch multiple column from multiple table in symfony doctrine

I want to fetch data from multiple tables but i am not getting the correct query in symfony3 doctrine. Please help me.
I wrote my doctrine query as follows -
$q = $this-> getDoctrine()-> getManager();
$query = $q->createQuery('
SELECT p.firstname , p.lastname , l.language
from UserBundle:Post p
from UserBundle:Language l
from UserBundle:UserLanguage u
where p.id = u.id and l.id = u.languageid
');
return $queryBuilder->getQuery()->getResult();
}
I am Finally able to solve this issue. This is the dql query to fetch different columns from multiple table with given condition.
$em = $this -> getDoctrine()->getManager();
$res = $em->createQuery(' SELECT p.firstname , p.lastname , l.language from UserBundle:Post p Join UserBundle:UserLanguage u with p.id = u.userid join UserBundle:Language l with l.id = u.languageid');
$result = $res->getResult();
return $this->render('UserBundle:Default:showLanguage.html.twig', array('user' => $result));

join querybuilder ax 2012 x++

Excuse my english (is not my native language)
Well, i wanna make this query (i make the temp table EMPL, the first temp table VEN is very easy but i don't see how to make the join)
SELECT 'CADORE_MP',EMPL.PERSONNELNUMBER, EMPL.NOMBRE, 0 AS CANTIDAD, VEN.MONTO FROM
(
SELECT VATNUM, SUM(INVOICEAMOUNT) AS MONTO FROM CUSTINVOICEJOUR
WHERE INVOICEDATE>=#FECHAI and INVOICEDATE<=#FECHAF
AND PAYMENT LIKE '%DIAS%'
AND CUSTGROUP LIKE 'EMP%'
AND REVERSE_GT=0 AND TAXTYPEDOCUMENTID='FC'
GROUP BY VATNUM) VEN
INNER JOIN
(
SELECT HW.PERSONNELNUMBER, HPIN.IDENTIFICATIONNUMBER, PRE.FIRSTNAME+' '+PRE.SECONDNAME+' '+PRE.FIRSTLASTNAME+' '+PRE.SECONDLASTNAME AS NOMBRE
FROM HcmPersonIdentificationNumber HPIN INNER JOIN HCMWORKER HW ON HPIN.PERSON=HW.PERSON AND HPIN.IDENTIFICATIONTYPE=5637146829
INNER JOIN PAYROLLEMPL PRE ON HW.PERSON=PRE.PERSON
INNER JOIN HCMEMPLOYMENT HE ON HW.RECID=HE.WORKER
LEFT JOIN PAYROLLLIQUIDATION PL ON HW.PERSONNELNUMBER=PL.EMPLID AND PL.DATELOW<#FECHAF
LEFT JOIN PAYROLLGROUPEMPLOYEES PRGE ON HW.PERSONNELNUMBER=PRGE.EMPLID AND GROUPSEMPLYEESID='CADORE_PQ'
WHERE HE.VALIDTO>='21541231' AND PL.EMPLID IS NULL AND PRGE.EMPLID IS NULL) EMPL ON VEN.VATNUM=EMPL.IDENTIFICATIONNUMBER
it have some parameters and other are constants.
so, i can do the two inner selects but later i can't do the join of this two temp tables
and i wanna know if someone can explain me the diference of join, exists join, no exists join. something like this
and if is posible to make when only wanna data from A but do not intersect with B
This is what i have
Query query;
QueryRun Run;
QueryBuildDataSource dataSourceHW;
QueryBuildDataSource dataSourceHPIN;
QueryBuildDataSource dataSourcePRE;
QueryBuildDataSource dataSourceHE;
QueryBuildDataSource dataSourcePL;
QueryBuildDataSource dataSourcePRGE;
str textDesc = "";
date FechaF;
FechaF = str2Date('21/03/2016',123);
query = new Query();
dataSourceHW = query.addDataSource(tableNum(HcmWorker));
dataSourceHPIN = dataSourceHW.addDataSource(tableNum(HcmPersonIdentificationNumber));
dataSourceHPIN.addLink(fieldNum(HcmWorker, Person), fieldNum(HcmPersonIdentificationNumber, Person));
dataSourceHPIN.addRange(fieldnum(HcmPersonIdentificationNumber,IdentificationType)).value('5637146829');
dataSourceHPIN.fetchMode(QueryFetchMode::One2One);
dataSourceHPIN.joinMode(JoinMode::InnerJoin);
dataSourcePRE = dataSourceHW.addDataSource(tableNum(PayRollEmpl), "PayRollEmpl");
dataSourcePRE.addLink(fieldNum(HcmWorker, Person), fieldNum(PayRollEmpl, Person));
dataSourcePRE.fetchMode(QueryFetchMode::One2One);
dataSourcePRE.joinMode(JoinMode::InnerJoin);
dataSourceHE = dataSourceHW.addDataSource(tableNum(HcmEmployment), "HcmEmployment");
dataSourceHE.addLink(fieldNum(HcmWorker, RecId), fieldNum(HcmEmployment, Worker));
dataSourceHE.addRange(fieldnum(HcmEmployment,ValidTo)).value(strFmt('%1' ,DateTimeUtil::maxValue()));
dataSourceHE.fetchMode(QueryFetchMode::One2One);
dataSourceHE.joinMode(JoinMode::InnerJoin);
dataSourcePL = dataSourceHW.addDataSource(tableNum(PayRollLiquidation));
dataSourcePL.addLink(fieldNum(HcmWorker, PersonnelNumber), fieldNum(PayRollLiquidation, EmplId));
dataSourcePL.addRange(fieldnum(PayRollLiquidation,DateLow)).value('21/03/2016');
dataSourcePL.fetchMode(QueryFetchMode::One2One);
dataSourcePL.joinMode(JoinMode::OuterJoin);
// this join under this dont work, indistinctly if i use it, always show me the same
// because of this i ask above about the data of table A only
dataSourcePRGE = dataSourceHW.addDataSource(tableNum(PayRollGroupEmployees));
dataSourcePRGE.addLink(fieldNum(HcmWorker, PersonnelNumber), fieldNum(PayRollGroupEmployees, EmplId));
dataSourcePRGE.addRange(fieldnum(PayRollGroupEmployees,GroupsEmplyeesId)).value('CADORE_PQ');
//dataSourcePRGE.addRange(fieldnum(PayRollGroupEmployees,EmplId)).value(SysQuery::valueEmptyString());
dataSourcePRGE.fetchMode(QueryFetchMode::One2One);
dataSourcePRGE.joinMode(JoinMode::NoExistsJoin);
will thanks you if someone help me

ZEND 2. Union . Add Limit to UNION query

I have an sql query like the one below and i would like to create this in Zend Framework 2.
( SELECT id AS id FROM exp_personal_data ORDER BY town ) UNION ( SELECT id AS id FROM pd_unregister )
I would like to have union and add to this LIMIT, ORDER BY etc.
$this->_select->combine($selectPdContest, 'union all');
When i write the query like this.
$this->_select->combine($selectPdContest, 'union all')->limit('10);
Query looks like this:
( SELECT id AS id FROM exp_personal_data ORDER BY town LIMIT 10 ) UNION ( SELECT id AS id FROM pd_unregister )
The limit is added only to firs select. I want the limit will to be added like this.
( SELECT id AS id FROM exp_personal_data ORDER BY town ) UNION ( SELECT id AS id FROM pd_unregister ) LIMIT 10
How make this in Zend framework 2?
Solution 1 (simple):
$adapter = $this->tableGateway->getAdapter();
$resultSet = $adapter->query("(SELECT user_id AS id FROM user ORDER BY id) UNION (SELECT account_id AS id FROM account) LIMIT 10",$adapter::QUERY_MODE_EXECUTE);
print_r($resultSet->toArray());die;
Solution 2 (Complex):
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Select;
//sql query first part
$adapter = $this->tableGateway->getAdapter();//the db connection adapter
$select = new Select('user');
$select->columns(array('id' => 'user_id'));
$select->order('id');
$sql = new Sql($adapter);
$statement = $sql->getSqlStringForSqlObject($select);
//sql query second part
$select2 = new Select('account');
$select2->columns(array('id' => 'account_id'));
$sql = new Sql($adapter);
$statement2 = $sql->getSqlStringForSqlObject($select2);
//combine the two statements into one
$unionQuery = sprintf('%s UNION %s','('.$statement = $sql->getSqlStringForSqlObject($select).')',
'('.$statement2 = $sql->getSqlStringForSqlObject($select2).') LIMIT 10');
//execute the union query
$resultSet = $adapter->query( $unionQuery, $adapter::QUERY_MODE_EXECUTE);
print_r($resultSet->toArray());die;
Add these lines will work,
$select1 = new Select();
$select1->combine($selectPdContest, 'union all');
$select3 = new Select();
$oneTwo = $select3->from(['sub' => $select1])->limit(10);

how to translate this query into Criteria?

I try to translate this query into Criteria (with Propel), but without success.
Can you help me please ?
SELECT DISTINCT (email)
FROM user, travail
WHERE travail.id_user = user.id_user
AND id_site = "1"
AND `droits` = "1"
This my Criteria query :
$c = new Criteria();
$c->add(self::DROITS, 1, Criteria::EQUAL);
$c->add(TravailPeer::ID_SITE, 1, CRITERIA::EQUAL);
$c->setDistinct(self::EMAIL);
How about this:
$c = new Criteria();
$c->add(UserPeer::DROITS, 1);
$c->addJoin(UserPeer::ID_USER, TravailPeer::ID_USER);
$c->add(TravailPeer::ID_SITE, 1);
$c->clearSelectColumns();
$c->addSelectColumn(UserPeer::EMAIL);
$c->setDistinct();
$rs = UserPeer::doSelectRS($c);
Hi You can use propel builder to translate not only this but any sql to the criteria. following is one of the online builder site.
http://propel.jondh.me.uk/

Resources