Convert MySQL with Subqueries to DQL 1.2 - mysql

Hi I have the following query from a previous question and need to convert it to DQL for Doctrine 1.2. However it turns out that DQL does not support subqueries in joins.
SELECT * FROM contact c
LEFT JOIN
(SELECT a1.contact_id, a1.date, a1.activity_type_id FROM activity a1
JOIN (SELECT contact_id, MAX(DATE) DATE FROM activity GROUP BY contact_id) a2
ON a1.contact_id = a2.contact_id AND a1.date = a2.date
) a
ON c.id = a.contact_id
WHERE a.activity_type_id = 2;
I'm trying to figure out how to do this another way without resorting to multiple queries.
Thanks.

Using doctrine, you should not nest subqueries into where condition using raw sql. You will get into trouble in more complex scenarios. Instead use createSubquery to explicitly tell doctrine about the subquery, let doctrine compile it to DQL and then nest it into your where condition. So your query should look something like this:
$q->from('Contact c')
->leftJoin('c.Activity a')
;
$subquery = $q->createSubquery()
->select("a1.contact_id, MAX(a1.date) a1.date")
->from("Activity a1")
->groupby("a1.contact_id")
;
$q->where('ROW (c.id, date) IN ('.$subquery->getDql().')')
->andWhere('a.activity_type_id = ?', $filterActivityTypeId)
;
Another example can be found here:
https://www.philipphoffmann.de/2012/08/29/a-bulletproof-pattern-for-creating-doctrine-subqueries-of-any-complexity/

Final query:
SELECT * FROM contact c
LEFT JOIN activity ON c.id = contact_id
WHERE ROW (c.id,DATE) IN (SELECT contact_id, MAX(date) date FROM activity GROUP BY contact_id)
AND activity_type_id = 2
Final DQL:
$q->from('Contact c')
->leftJoin('c.Activity a')
->where('ROW (c.id, date) IN (SELECT a1.contact_id, MAX(a1.date) a1.date FROM Activity a1 GROUP BY a1.contact_id)')
->andWhere('a.activity_type_id = ?', $filterActivityTypeId);

Related

How to implement sql query in yii2 search model?

I have following query:
SELECT hs.*FROM hire_screening hs
INNER JOIN (SELECT resume_id,MAX(created_date) AS MaxDateTime
FROM hire_screening GROUP BY resume_id) hire_screening
ON hs.resume_id = hire_screening.resume_id
AND hs.created_date = hire_screening.MaxDateTime
I tried this:
$query = HireScreening::find()
->select(["hs.resume_id","MAX(hs.created_date) AS MaxDateTime"])
->innerJoin('hire_screening as hs','hs.resume_id = hire_screening.resume_id')
->where(['hire_screening.created_date' => 'MaxDateTime'])
->orderBy(['(hs.created_date)' => SORT_DESC])
->groupBy(['hs.resume_id']);
When I use group by the result shows the first values of each 'resume_id' in the order that stored in the table. I just need the most latest distinct resume_id 's according to created_date.
How can I implement this query in yii2 search model? Please help.
If you want to execute the raw sql query means, then you can use
createCommand function. But it will return the array so in grid you should use array data provider.
$array= Yii::$app->db->createCommand("
SELECT hs.*FROM hire_screening hs
INNER JOIN (SELECT resume_id,MAX(created_date) AS MaxDateTime
FROM hire_screening GROUP BY resume_id) hire_screening
ON hs.resume_id = hire_screening.resume_id
AND hs.created_date = hire_screening.MaxDateTime")->queryAll();

Mysql Group By and ABS function Stack

I have sql code like this, when I execute the code with GROUP BY it just shows record number one and it doesn't use the ABS function. Anyone can help me please?
SELECT *, `tblLifeAgency`.`AgencyName`, `mlp`.`Basic40`, `mlp`.`ADB40`, `mlp`.`CiAccel40`, `mlp`.`Basic50`, `mlp`.`ADB50`, `mlp`.`CiAccel50`, `mlp`.`Basic60`, `mlp`.`ADB60`, `mlp`.`CiAccel60`
FROM (`tblPackage`)
INNER JOIN `tblMatrixLifePackage` mlp ON `mlp`.`PackageID` = `tblPackage`.`PackageID`
INNER JOIN `tblCompany` ON `tblPackage`.`CompanyID` = `tblCompany`.`CompanyID`
INNER JOIN `tblLifeAgency` ON `tblLifeAgency`.`CompanyID` = `tblCompany`.`CompanyID`
AND `tblPackage`.`IsActive` = '1'
WHERE `tblPackage`.`PackageType` = '2'
GROUP BY tblPackage.CompanyID
ORDER BY abs(tblPackage.TotalPremi - 250000)
GROUP BY groups your records. If you have record values, you have to decides which result to show as a summary for a line. For example, you can take all values in one group as positive (ABS) and sum them (SUM). Then try converting this pattern into your case (to understand better):
SELECT
`group`,
ABS(
SUM(`value`)) AS `sum`
FROM my_table
GROUP BY `group`

Subquery for SQL

I need assistance in joining the two query statements together using subquery. I am confused on how I can combine the two together. I appreciate the help.
SELECT * FROM MEDICAL_PROCEDURE
JOIN PROCEDURE_CATEGORY ON medical_procedure.procedure_category_id = PROCEDURE_CATEGORY.PROCEDURE_CATEGORY_ID;
SELECT
Medical_procedure.medical_procedure_id,
COUNT(procedure_tool_supply.medical_procedure_id) AS Supply_Needed
FROM Procedure_tool_supply
JOIN Medical_Procedure on Procedure_tool_supply.medical_procedure_id = Medical_procedure.medical_procedure_id
GROUP BY Procedure_tool_supply.medical_procedure_id
HAVING COUNT(Procedure_tool_supply.medical_procedure_id) < 3;
Can't really test without test data, but this should work. Hopefully I figured out correctly what you're trying to do:
SELECT *
FROM
MEDICAL_PROCEDURE P
JOIN PROCEDURE_CATEGORY C ON
P.procedure_category_id = C.PROCEDURE_CATEGORY_ID
cross apply (
SELECT
COUNT(T.medical_procedure_id) AS Supply_Needed
FROM
Procedure_tool_supply T
where
T.medical_procedure_id = P.medical_procedure_id
GROUP BY
T.medical_procedure_id
HAVING
COUNT(T.medical_procedure_id) < 3
) T
It's not clear what you are trying to achieve. But if your intent is to include the derived Supply_Needed column from the second query on each row from the first query, and to restrict the rows returned to those that have a medical_procedure_id value returned by the second query, then...
you could do something like this:
SELECT mp.*
, pc.*
, ct.Supply_Needed
FROM MEDICAL_PROCEDURE mp
JOIN PROCEDURE_CATEGORY pc
ON mp.procedure_category_id = pc.PROCEDURE_CATEGORY_ID
JOIN ( SELECT pr.medical_procedure_id
, COUNT(ts.medical_procedure_id) AS Supply_Needed
FROM Procedure_tool_supply ts
JOIN Medical_Procedure pr
ON ts.medical_procedure_id = pr.medical_procedure_id
GROUP BY ts.medical_procedure_id
HAVING COUNT(ts.medical_procedure_id) < 3
) ct
ON ct.medical_procedure_id = mp.medical_procedure_id

MAX() Function not working as expected

I've created sqlfiddle to try and get my head around this http://sqlfiddle.com/#!2/21e72/1
In the query, I have put a max() on the compiled_date column but the recommendation column is still coming through incorrect - I'm assuming that a select statement will need to be inserted on line 3 somehow?
I've tried the examples provided by the commenters below but I think I just need to understand this from a basic query to begin with.
As others have pointed out, the issue is that some of the select columns are neither aggregated nor used in the group by clause. Most DBMSs won't allow this at all, but MySQL is a little relaxed on some of the standards...
So, you need to first find the max(compiled_date) for each case, then find the recommendation that goes with it.
select r.case_number, r.compiled_date, r.recommendation
from reporting r
join (
SELECT case_number, max(compiled_date) as lastDate
from reporting
group by case_number
) s on r.case_number=s.case_number
and r.compiled_date=s.lastDate
Thank you for providing sqlFiddle. But only reporting data is given. we highly appreciate if you give us sample data of whole tables.
Anyway, Could you try this?
SELECT
`case`.number,
staff.staff_name AS ``case` owner`,
client.client_name,
`case`.address,
x.mx_date,
report.recommendation
FROM
`case` INNER JOIN (
SELECT case_number, MAX(compiled_date) as mx_date
FROM report
GROUP BY case_number
) x ON x.case_number = `case`.number
INNER JOIN report ON x.case_number = report.case_number AND report.compiled_date = x.mx_date
INNER JOIN client ON `case`.client_number = client.client_number
INNER JOIN staff ON `case`.staff_number = staff.staff_number
WHERE
`case`.active = 1
AND staff.staff_name = 'bob'
ORDER BY
`case`.number ASC;
Check below query:
SELECT c.number, s.staff_name AS `case owner`, cl.client_name,
c.address, MAX(r.compiled_date), r.recommendation
FROM case c
INNER JOIN (SELECT r.case_number, r.compiled_date, r.recommendation
FROM report r ORDER BY r.case_number, r.compiled_date DESC
) r ON r.case_number = c.number
INNER JOIN client cl ON c.client_number = cl.client_number
INNER JOIN staff s ON c.staff_number = s.staff_number
WHERE c.active = 1 AND s.staff_name = 'bob'
GROUP BY c.number
ORDER BY c.number ASC
SELECT
case.number,
staff.staff_name AS `case owner`,
client.client_name,
case.address,
(select MAX(compiled_date)from report where case_number=case.number),
report.recommendation
FROM
case
INNER JOIN report ON report.case_number = case.number
INNER JOIN client ON case.client_number = client.client_number
INNER JOIN staff ON case.staff_number = staff.staff_number
WHERE
case.active = 1 AND
staff.staff_name = 'bob'
GROUP BY
case.number
ORDER BY
case.number ASC
try this

MySQL Inner Join with where clause sorting and limit, subquery?

Everything in the following query results in one line for each invBlueprintTypes row with the correct information. But I'm trying to add something to it. See below the codeblock.
Select
blueprintType.typeID,
blueprintType.typeName Blueprint,
productType.typeID,
productType.typeName Item,
productType.portionSize,
blueprintType.basePrice * 0.9 As bpoPrice,
productGroup.groupName ItemGroup,
productCategory.categoryName ItemCategory,
blueprints.productionTime,
blueprints.techLevel,
blueprints.researchProductivityTime,
blueprints.researchMaterialTime,
blueprints.researchCopyTime,
blueprints.researchTechTime,
blueprints.productivityModifier,
blueprints.materialModifier,
blueprints.wasteFactor,
blueprints.maxProductionLimit,
blueprints.blueprintTypeID
From
invBlueprintTypes As blueprints
Inner Join invTypes As blueprintType On blueprints.blueprintTypeID = blueprintType.typeID
Inner Join invTypes As productType On blueprints.productTypeID = productType.typeID
Inner Join invGroups As productGroup On productType.groupID = productGroup.groupID
Inner Join invCategories As productCategory On productGroup.categoryID = productCategory.categoryID
Where
blueprints.techLevel = 1 And
blueprintType.published = 1 And
productType.marketGroupID Is Not Null And
blueprintType.basePrice > 0
So what I need to get in here is the following table with the columns below it so I can use the values timestamp and sort the entire result by profitHour
tablename: invBlueprintTypesPrices
columns: blueprintTypeID, timestamp, profitHour
I need this information with the following select in mind. Using a select to show my intention of the JOIN/in-query select or whatever that can do this.
SELECT * FROM invBlueprintTypesPrices
WHERE blueprintTypeID = blueprintType.typeID
ORDER BY timestamp DESC LIMIT 1
And I need the main row from table invBlueprintTypes to still show even if there is no result from the invBlueprintTypesPrices. The LIMIT 1 is because I want the newest row possible, but deleting the older data is not a option since history is needed.
If I've understood correctly I think I need a subquery select, but how to do that? I've tired adding the exact query that is above with a AS blueprintPrices after the query's closing ), but did not work with a error with the
WHERE blueprintTypeID = blueprintType.typeID
part being the focus of the error. I have no idea why. Anyone who can solve this?
You'll need to use a LEFT JOIN to check for NULL values in invBlueprintTypesPrices. To mimic the LIMIT 1 per TypeId, you can use the MAX() or to truly make sure you only return a single record, use a row number -- this depends on whether you can have multiple max time stamps for each type id. Assuming not, then this should be close:
Select
...
From
invBlueprintTypes As blueprints
Inner Join invTypes As blueprintType On blueprints.blueprintTypeID = blueprintType.typeID
Inner Join invTypes As productType On blueprints.productTypeID = productType.typeID
Inner Join invGroups As productGroup On productType.groupID = productGroup.groupID
Inner Join invCategories As productCategory On productGroup.categoryID = productCategory.categoryID
Left Join (
SELECT MAX(TimeStamp) MaxTime, TypeId
FROM invBlueprintTypesPrices
GROUP BY TypeId
) blueprintTypePrice On blueprints.blueprintTypeID = blueprintTypePrice.typeID
Left Join invBlueprintTypesPrices blueprintTypePrices On
blueprintTypePrice.TypeId = blueprintTypePrices.TypeId AND
blueprintTypePrice.MaxTime = blueprintTypePrices.TimeStamp
Where
blueprints.techLevel = 1 And
blueprintType.published = 1 And
productType.marketGroupID Is Not Null And
blueprintType.basePrice > 0
Order By
blueprintTypePrices.profitHour
Assuming you might have the same max time stamp with 2 different records, replace the 2 left joins above with something similar to this getting the row number:
Left Join (
SELECT #rn:=IF(#prevTypeId=TypeId,#rn+1,1) rn,
TimeStamp,
TypeId,
profitHour,
#prevTypeId:=TypeId
FROM (SELECT *
FROM invBlueprintTypesPrices
ORDER BY TypeId, TimeStamp DESC) t
JOIN (SELECT #rn:=0) t2
) blueprintTypePrices On blueprints.blueprintTypeID = blueprintTypePrices.typeID AND blueprintTypePrices.rn=1
You don't say where you are putting the subquery. If in the select clause, then you have a problem because you are returning more than one value.
You can't put this into the from clause directly, because you have a correlated subquery (not allowed).
Instead, you can put it in like this:
from . . .
(select *
from invBLueprintTypesPrices ibptp
where ibtp.timestamp = (select ibptp2.timestamp
from invBLueprintTypesPrices ibptp2
where ibptp.blueprintTypeId = ibptp2.blueprintTypeId
order by timestamp desc
limit 1
)
) ibptp
on ibptp.blueprintTypeId = blueprintType.TypeID
This identifies the most recent records for all the blueprintTypeids in the subquery. It then joins in the one that matches.