Convert from SQL to DQL - repository

Can you please convert it to DQL :
SELECT molecule.cas, molecule.id_molecule, molecule.statutvlep8h, statutvlepct,
vlep8h_mg, vlepct_mg,molecule.unitevlep, prelevement.id_laboratoire
FROM thym_dev.molecule
INNER JOIN thym_dev.prelevement
WHERE molecule.id_molecule = prelevement.id_molecule
UNION ALL
SELECT molecule.cas, molecule.id_molecule, molecule.statutvlep8h, statutvlepct,
vlep8h_mg, vlepct_mg,molecule.unitevlep, analyse.id_laboratoire
FROM thym_dev.molecule
INNER JOIN thym_dev.analyse
WHERE molecule.id_molecule = analyse.id_molecule;

I get the answer :
$queryBuilder0 = "
SELECT molecule.molecule, molecule.cas, molecule.statutvlep8h,molecule.statutvlepct,molecule.vlep8hMg, molecule.vlepctMg,molecule.unitevlep,IDENTITY(prelevement.laboratoire)
FROM AppBundle:Molecule molecule
INNER JOIN AppBundle:Prelevement prelevement
WHERE prelevement.molecule= molecule.id
";
$queryBuilder1 = "
SELECT molecule.molecule , molecule.cas, molecule.statutvlep8h, molecule.statutvlepct, molecule.vlep8hMg, molecule.vlepctMg,molecule.unitevlep,IDENTITY(analyse.laboratoire)
FROM AppBundle:Molecule molecule
INNER JOIN AppBundle:Analyse analyse
WHERE analyse.molecule= molecule.id
";
$results = array_merge($this->_em->createQuery($queryBuilder0)->getResult(), $this->_em->createQuery($queryBuilder1)->getResult());

Related

EclipseLink/TopLink full outer join instead left join

On model Card can have or not CardHolder ( 1:1 ), and I would like getting every cards filter by issuer linked to actived cardHolders plus cards without cardHolders, so I need a full outer join. Although the query below translate to left join returning just cards with cardHolders
final ExpressionBuilder builder = new ExpressionBuilder( Card.class );
Expression queryExp = builder.get( "cardIssuer" ).equal( cardIssuer );
queryExp = queryExp.and( builder.get( "cardStatus" ).get( "statusType" ).equal( "ACTIVATED" ) );
queryExp = queryExp.and( builder.getAllowingNull( "cardHolder" )isNull().or(
builder.get( "cardHolder" ).get( "status" ).get( "status" ).equal( "ACTIVE" ) ) );
Expression orderExpression = builder.get( "cardHolder" ).get( "surname" ).descending();
return getMultiple( queryExp, pageable , Card.class, orderExpression );
Translate query is
SELECT COUNT(t0.CARD_ID) FROM CARD t0 LEFT JOIN CARD_HOLDER t3
ON (t3.CARD_HOLDER_ID = t0.CARD_HOLDER_ID), CARD_HOLDER_STATUS t2, CARD_STATUS t1
WHERE (((((t0.CARD_ISSUER_ID = 10006) AND (t1.STATUS_TYPE = 'ACTIVATED')) AND (t2.STATUS = 'ACTIVE'))
AND (t0.CARD_ID IN ('52683','52692')))
AND ((t1.CARD_STATUS_ID = t0.CARD_STATUS_ID) AND (t2.STATUS_ID = t3.STATUS_ID)))
Due to JPA version the outer join is not properly done, so I found a way through native queries
#NamedNativeQueries( {
#NamedNativeQuery( name = Card.USER_DIRECTORY_BASE,
query = "select * from card c full outer join card_holder ch on c.card_holder_id = ch.card_holder_id "
+ "where c.CARD_ISSUER_ID = ?1 and c.card_status_id = 1 and ( ch.STATUS_ID = 1 or c.CARD_HOLDER_ID is null) "
+ "order by ch.FORENAME asc",
resultClass = Card.class ),
#NamedNativeQuery( name = Card.USER_DIRECTORY_BASE_COUNT,
query = "select count(*) from card c full outer join card_holder ch on c.card_holder_id = ch.card_holder_id "
+ "where c.CARD_ISSUER_ID = ?1 and c.card_status_id = 1 and ( ch.STATUS_ID = 1 or c.CARD_HOLDER_ID is null) "
+ "order by ch.FORENAME asc" )
} )
And getting results
Query query = em.createNamedQuery( Card.USER_DIRECTORY_BASE);
query.setParamenter(1,10000);
query.getResultList();

convert sql subquery with multiple joins to linq

I'm having trouble working in my subselect into LINQ. Here is the SQL followed by the LINQ. The SQL Query runs fine. The problem is incorporating the subquery. Any assistance would be appreciated:
SELECT DISTINCT
cic.CommitmentItemCategoryName + '( ' + cicType.CommitmentItemCategoryTypeName + ' )' AS displayCategory
, 'CategoryType_' + CAST(cic.CommitmentItemCategoryID AS VARCHAR(10)) AS displayCategoryID
, ISNULL(vwPAD.DollarsAllocated, 0) AS DisplayDollarsAllocated
,cic.CommitmentItemCategoryID
FROM
tblCommitmentItemCategory cic
LEFT OUTER JOIN
tblCommitmentItemCategoryType cicType ON cic.CommitmentItemCategoryTypeID = cicType.CommitmentItemCategoryTypeID
LEFT OUTER JOIN
tblAccountDirectToCommitmentItemCategory adToCIC ON adToCIC.CommitmentItemCategoryID IN (SELECT CommitmentItemCategoryID FROM tblCommitmentItemCategory)
LEFT OUTER JOIN
vw_ParentAccountDollarsAllocatedByCommitmentItemCategory vwPAD ON vwPAD.FiscalYear = 2015
AND cic.CommitmentItemCategoryID = vwPAD.CommitmentItemCategoryID
AND vwPAD.AccountDirectParentID = 19
WHERE
adToCIC.AccountDirectParentID = 19
ORDER BY
displayCategory
var queryInner = from cic in MyContext.tblCommitmentItemCategory
select new
{
cic.CommitmentItemCategoryID
};
var queryDollars = (from cic in MyContext.tblCommitmentItemCategory
join cicType in MyContext.tblCommitmentItemCategoryType
on cic.CommitmentItemCategoryTypeID equals cicType.CommitmentItemCategoryTypeID
into t2
from cicType in t2.DefaultIfEmpty()
join adToCIC in MyContext.tblAccountDirectToCommitmentItemCategory
//What goes here?
on ...
// on cic.CommitmentItemCategoryID equals adToCIC.CommitmentItemCategoryID
into t3
from adToCIC in t3.DefaultIfEmpty()
join vw in MyContext.vw_ParentAccountDollarsAllocatedByCommitmentItemCategory
on new { FiscalYear = currentFiscalYear, CommitmentItemCategory = cic.CommitmentItemCategoryID, ParentAccountID = currentParentAccountID }
equals new { FiscalYear = vw.FiscalYear, CommitmentItemCategory = vw.CommitmentItemCategoryID, ParentAccountID = vw.AccountDirectParentID }
into t
from vw in t.DefaultIfEmpty()
where adToCIC.AccountDirectParentID == currentParentAccountID
let displayCategory = cic.CommitmentItemCategoryName + " ( " + cicType.CommitmentItemCategoryTypeName + " )"
// Called CategoryType but it's actually the ID below
let displayCategoryTypeID = "CategoryType_" + cic.CommitmentItemCategoryID.ToString()
//let displayCategoryTypeID = "CategoryType!" + cic.CommitmentItemCategoryID + "_" + adToCIC.AccountDirectToCommitmentItemCategoryID.ToString()
let displayDollarsAllocated = vw.DollarsAllocated == null ? 0 : vw.DollarsAllocated
orderby cic.CommitmentItemCategoryName
select new
{
displayCategory,
displayCategoryTypeID,
cic.CommitmentItemCategoryID,
displayDollarsAllocated
}).Distinct();
Can you convert queryInner to a join? Then use that result in the larger query:
var queryInner =
from atcic in MyContext.tblAccountDirectToCommitmentItemCategory
join cic in MyContext.tblCommitmentItemCategory on atcic.CommitmentItemCategoryID equals cic.CommitmentItemCategoryID
select atcic;
And in the big query:
join adToCIC in queryInner into t3
from adToCIC in t3.DefaultIfEmpty()

DRUPAL db_or adding AND between multiple variables

I have inherited an application that is using the drupal filtering system to find results. The user can select to search the 'campus_location' column but when they enter multiple variables, it adds an AND between the condition.
Here is the printed version of the query generated by drupal:
SELECT * FROM champs c INNER JOIN users u ON u.uid = c.uid LEFT OUTER JOIN champs_rsvp r
ON r.uid = c.uid LEFT OUTER JOIN champs_checklists cl
ON cl.id = c.checklist_id LEFT OUTER JOIN node en
ON en.uid = u.uid AND en.type = 'getting_started_event'
LEFT OUTER JOIN node sn ON sn.uid = u.uid
AND sn.type = 'success_story'
LEFT OUTER JOIN champs_action_steps cas
ON cas.uid = u.uid
WHERE ( (c.campus_location LIKE 'Flint' ESCAPE '\\') )
**AND**( (c.campus_location LIKE 'Ann Arbor' ESCAPE '\\') )
I need the last AND to be an OR so it looks like this:
SELECT * FROM champs c INNER JOIN users u ON u.uid = c.uid LEFT OUTER JOIN champs_rsvp r
ON r.uid = c.uid LEFT OUTER JOIN champs_checklists cl
ON cl.id = c.checklist_id LEFT OUTER JOIN node en
ON en.uid = u.uid AND en.type = 'getting_started_event'
LEFT OUTER JOIN node sn ON sn.uid = u.uid
AND sn.type = 'success_story'
LEFT OUTER JOIN champs_action_steps cas
ON cas.uid = u.uid
WHERE ( (c.campus_location LIKE 'Flint' ESCAPE '\\') )
OR( (c.campus_location LIKE 'Ann Arbor' ESCAPE '\\') )
Which produces the correct results.
Here is the code that I inherited where it looks over the words in the search box. I just can't seem to figure out where it is adding the variables where it is putting the AND.
$words = explode(",", $_SESSION['form_state']['values']['filter']);
foreach($words as $word)
{
$or = db_or();
foreach($cols as $col)
{
$table = 'c';
if(in_array($col, array('completed_date', 'score')))
$table = 'cl';
elseif(in_array($col, array('name', 'mail')))
$table = 'u';
elseif($col == 'date')
$table = 'r';
elseif(in_array($col, array('announce', 'num_success_stories', 'num_action_steps'))) //can't put these in WHERE clause. Need to go in HAVING.
continue;
echo $word;
$or = $or->condition($table . '.' . $col, champs_make_like_sql($word), 'LIKE');
}
$result = $query->condition($or);
}

Error in FROM clause: near '{'. Unable to parse query text

I'm trying to execute the following query for a Dataset:
SELECT
S.CUSIP, S.SecName,
ISNULL(RA.FinInstCode, '') AS RemarketingAgent,
S.IssueDate, S.MaturityDate, F2.FinInstName AS Trustee,
CASE WHEN SC1.ExpirationDate IS NULL
THEN '' ELSE ISNULL(F1.FinInstCode, '') END
AS CreditProvider,
CASE WHEN SC1.ExpirationDate IS NULL
THEN '' ELSE ISNULL(C1.CreditEnhancementCode, '') END
AS CreditType,
SC1.ExpirationDate AS CreditExpirationDate,
SC1.RefNum AS RefNumber
FROM
dbo.SecurityCreditEnhancementProvider SC1,
dbo.FinInst F1,
dbo.LUCreditEnhancement C1,
{ oj { oj dbo.Security S
LEFT OUTER JOIN
dbo.FinInst F2 ON S.TrusteeID = F2.FinInstID }
LEFT OUTER JOIN
dbo.FinInst RA ON S.RemarketingAgentID = RA.FinInstID }
WHERE
S.SecID = SC1.SecID
AND
SC1.CreditProviderID = F1.FinInstID
AND
SC1.CreditEnhancementID = C1.CreditEnhancementID
AND
C1.CreditEnhancementCode = 'LOC' OR
C1.CreditEnhancementCode = 'LIQUIDITY'
AND
(S.ActiveFlag = 'A')
AND
(S.SecTypeID NOT IN (4, 7))
ORDER BY CreditExpirationDate
When trying to run the query the error I get is " Error in FROM clause near:
'{' . Unable to parse query. "
Any help to fix this issue would be most appreciated.
Thanks,
EDIT 1: This is what is looks like after query designer changes the code:
FROM { oj { oj { oj { oj { oj dbo.SecurityCreditEnhancementProvider SC1 LEFT OUTER JOIN
dbo.FinInst F1 ON SC1.CreditProviderID = F1.FinInstID } LEFT OUTER JOIN
dbo.LUCreditEnhancement C1 ON SC1.CreditEnhancementID = C1.CreditEnhancementID } LEFT OUTER JOIN
dbo.Security S ON S.SecID = SC1.SecID } LEFT OUTER JOIN
dbo.FinInst F2 ON S.TrusteeID = F2.FinInstID } LEFT OUTER JOIN
dbo.FinInst RA ON S.RemarketingAgentID = RA.FinInstID }
Thanks all for there help.
Formatting code in a case like this might be helpful. you had incorrect syntax in your FROM clause. I also updated the query to use JOIN Syntax on all tables instead of using commas between your tables.
SELECT S.CUSIP
, S.SecName
, ISNULL(RA.FinInstCode, '') AS RemarketingAgent
, S.IssueDate
, S.MaturityDate
, F2.FinInstName AS Trustee
, CASE WHEN SC1.ExpirationDate IS NULL THEN '' ELSE ISNULL(F1.FinInstCode, '') END AS CreditProvider
, CASE WHEN SC1.ExpirationDate IS NULL THEN '' ELSE ISNULL(C1.CreditEnhancementCode, '') END AS CreditType
, SC1.ExpirationDate AS CreditExpirationDate
, SC1.RefNum AS RefNumber
FROM dbo.SecurityCreditEnhancementProvider SC1
LEFT JOIN dbo.FinInst F1
ON SC1.CreditProviderID = F1.FinInstID
LEFT JOIN dbo.LUCreditEnhancement C1
ON SC1.CreditEnhancementID = C1.CreditEnhancementID
LEFT JOIN dbo.Security S
ON S.SecID = SC1.SecID
LEFT OUTER JOIN dbo.FinInst F2
ON S.TrusteeID = F2.FinInstID
LEFT OUTER JOIN dbo.FinInst RA
ON S.RemarketingAgentID = RA.FinInstID
WHERE (C1.CreditEnhancementCode = 'LOC' OR C1.CreditEnhancementCode = 'LIQUIDITY' )
AND (S.ActiveFlag = 'A')
AND (S.SecTypeID NOT IN (4, 7))
ORDER BY CreditExpirationDate

Zend how do I create a left join

How do I turn this left join query:
select advertisercontest.*, advertiseraccount.advertiserid, advertiseraccount.companyname
from advertisercontest
left join advertiseraccount on advertiseraccount.loginid = advertisercontest.loginid
where advertisercontest.golive is not NULL;
into a left join in Zend?
You could do as follows:
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select->from('advertisercontest', '*')
->joinLeft(
'advertiseraccount',
'advertiseraccount.loginid = advertisercontest.loginid',
array('advertiseraccount.advertiserid', 'advertiseraccount.companyname')
)
->where('advertisercontest.golive is not NULL');;
$result = $db->fetchAll($select);
var_dump($result);
Here is the Zend_Db_Select documentation.