Is there a way that I can combine these two queries:
FIRST QUERY
select top 100
WORK.pzInsKey,
WORK.pyID,
PARTY.MacID,
PARTY.OtherPartyID,
PARTY.CustomerEmail,
ACCOUNT.AccountNumber,
ACCOUNT.AccountName,
ACCOUNT.AdviserCode,
ACCOUNT.AdviserName,
ACCOUNT.DealerCode,
ACCOUNT.DealerName,
ACCOUNT.PrimaryAccount,
ACCOUNT.ProductCategory,
ACCOUNT.ProductCode,
ACCOUNT.ProductDescription,
ACCOUNT.RegisteredState,
DOCUMENT.UDOCID
from
workTable WORK,
partyTable PARTY,
accountTable ACCOUNT,
documentTable DOCUMENT,
notesTable NOTES
where WORK.pzInsKey = PARTY.pxInsIndexedKey
and WORK.pzInsKey = ACCOUNT.pxInsIndexedKey
and WORK.pyID = DOCUMENT.CaseID
and SECOND QUERY
SELECT top 100
BusinessAreaTbl.businessarea,
ProcessTbl.process,
SubProcessTbl.subprocess
FROM workTable WORK
LEFT OUTER JOIN (SELECT DISTINCT Product_ID businessarea_id, Product businessarea from CaseTypesTable) BusinessAreaTbl
ON WORK.RequestBusinessArea#1 = BusinessAreaTbl.businessarea_id
LEFT OUTER JOIN (SELECT DISTINCT Process_ID, Process, Product_ID businessarea_id from CaseTypesTable) ProcessTbl
ON WORK.RequestProcess#1 = ProcessTbl.process_id
AND ProcessTbl.businessarea_id = WORK.RequestBusinessArea#1
LEFT OUTER JOIN (SELECT DISTINCT SubProcess_ID, SubProcess, Product_ID businessarea_id, Process_ID from CaseTypesTable) SubProcessTbl
ON WORK.RequestSubProcess#1 = SubProcessTbl.subprocess_id
AND SubProcessTbl.businessarea_id = WORK.RequestBusinessArea#1
AND SubProcessTbl.process_id = WORK.RequestProcess#1
It's basically two queries which produce separate results, but each query includes data from the workTable. In the 2nd query, the workTable data is derived from the CaseTypesTable.
I essentially just want the businessarea, process, and subprocess fields to be included with the results of the first query.
Thanks in advance for any help.
This should work:
(SELECT top 100
w.pzInsKey,
w.pyID,
p.MacID,
p.OtherPartyID,
p.CustomerEmail,
a.AccountNumber,
a.AccountName,
a.AdviserCode,
a.AdviserName,
a.DealerCode,
a.DealerName,
a.PrimaryAccount,
a.ProductCategory,
a.ProductCode,
a.ProductDescription,
a.RegisteredState,
d.UDOCID
FROM workTable w
LEFT JOIN partyTable p
ON w.pzInsKey = p.pxInsIndexedKey
LEFT JOIN accountTable a
ON w.pzInsKey = a.pxInsIndexedKey
LEFT JOIN documentTable d
ON w.pyID = d.CaseID)
UNION
(SELECT top 100
ba.businessarea,
pr.process,
spr.subprocess
FROM workTable w
LEFT OUTER JOIN (SELECT DISTINCT Product_ID businessarea_id, Product businessarea from CaseTypesTable) BusinessAreaTbl ba
ON w.RequestBusinessArea#1 = ba.businessarea_id
LEFT OUTER JOIN (SELECT DISTINCT Process_ID, Process, Product_ID businessarea_id from CaseTypesTable) ProcessTbl pr
ON w.RequestProcess#1 = pr.process_id
AND pr.businessarea_id = w.RequestBusinessArea#1
LEFT OUTER JOIN (SELECT DISTINCT SubProcess_ID, SubProcess, Product_ID businessarea_id, Process_ID from CaseTypesTable) SubProcessTbl spr
ON w.RequestSubProcess#1 = spr.subprocess_id
AND spr.businessarea_id = w.RequestBusinessArea#1
AND spr.process_id = w.RequestProcess#1))
Use the keyword UNION to combine two or more seperate SELECT statements.
Related
I am trying to create a SQL query where I take in 3 tables, and count all the rows.
Unfortunately I can't seem to get a response from this query.
$sqlQuery ="SELECT COUNT(*)
tblCampaignLists.CampaignListId,
tblCampaignLists.ClientId,
tblCampaignLists.CampaignId,
tblCampaignLists.CampaignFilter,
tblClients.ClientName,
tblClients.ClientState,
tblClients.ClientCreationDate,
tblClients.ClientEmail,
tblClients.ClientAddressCounty,
tblCampaigns.CampaignName,
tblCampaigns.CampaignDescription,
tblCampaigns.OrganisationId,
tblCampaignFilters.FilterId,
tblCampaignFilters.Section,
tblCampaignFilters.TitleIds,
tblCampaignFilters.FeatureIds,
tblCampaignFilters.EditionIds,
tblCampaignFilters.NotInEditionId
FROM
tblCampaignLists
LEFT JOIN tblClients ON tblClients.ClientId = tblCampaignLists.ClientId
LEFT JOIN tblCampaigns ON tblCampaigns.CampaignId = tblCampaignLists.CampaignId
LEFT JOIN tblCampaignFilters ON tblCampaignFilters.FilterId = tblCampaignLists.CampaignFilter
What can I do to get the number of rows?
Only use count:
$sqlQuery ="SELECT COUNT(*)
FROM
tblCampaignLists
LEFT JOIN tblClients ON tblClients.ClientId = tblCampaignLists.ClientId
LEFT JOIN tblCampaigns ON tblCampaigns.CampaignId = tblCampaignLists.CampaignId
LEFT JOIN tblCampaignFilters ON tblCampaignFilters.FilterId = tblCampaignLists.CampaignFilter"
How can I access data from an outer table in a SELECT, and use it in an WHERE inside a JOIN estructure?
Below is the current query:
SELECT
cvl.id caracteristica_valor_id,
cvl.nome caracteristica_valor_nome,
cvl.valor caracteristica_valor_valor,
ctp.id caracteristica_tipo_id,
ctp.nome caracteristica_tipo_nome,
ctp.codigo caracteristica_tipo_codigo,
ctp.tipo caracteristica_tipo_tipo,
COUNT(DISTINCT var.id_perfil_produto) quantidade_itens
FROM
caracteristica_variacao cvr
INNER JOIN caracteristica_valor cvl ON cvl.id = cvr.id_caracteristica_valor
INNER JOIN caracteristica_tipo ctp ON ctp.id = cvl.id_caracteristica_tipo
INNER JOIN variacao var ON var.id = cvr.id_variacao
INNER JOIN(
SELECT DISTINCT
ppr.id perfil_produto_id
FROM
perfil_produto ppr
INNER JOIN produto pro ON pro.id = ppr.id_produto
INNER JOIN(
SELECT ppr2.id AS id_perfil_sub,a
COUNT(var.id) AS qtd_variacoes,
SUM(var.quantidade_estoque) AS quantidade_estoque,
COALESCE(SUM(var.quantidade_estoque_reservada),0) AS quantidade_estoque_reservada,
MIN(var.disponibilidade) AS disponibilidade,
MIN(var.frete_gratis) AS frete_gratis,
MIN(var.preco_venda) AS preco_venda,
MAX(var.preco_listagem) AS preco_listagem
FROM
variacao var
LEFT JOIN perfil_produto ppr2 ON ppr2.id = var.id_perfil_produto
LEFT JOIN caracteristica_variacao cvr_1 ON cvr_1.id_variacao = var.id
LEFT JOIN caracteristica_valor cvl_1 ON cvl_1.id = cvr_1.id_caracteristica_valor
LEFT JOIN caracteristica_tipo ctp_1 ON ctp_1.id = cvl_1.id_caracteristica_tipo
WHERE
var.disponibilidade = 1
AND(
ctp_1.codigo = 'tamanho' AND cvl_1.valor IN('p')
)
GROUP BY
ppr2.id
) AS grp_var ON grp_var.id_perfil_sub = ppr.id
INNER JOIN produto_categoria prc ON pro.id = prc.produto_id
INNER JOIN categoria cat ON prc.categoria_id = cat.id
WHERE
pro.disponibilidade = 1 AND prc.categoria_id IN (164, 165, 166)
) AS produto ON produto.perfil_produto_id = var.id_perfil_produto
GROUP BY
cvl.id
ORDER BY
ctp.tipo ASC,
ctp.id
I need the field ctp.codigo from the outer table inside thist part:
WHERE
var.disponibilidade = 1
AND(
ctp_1.codigo = 'tamanho' AND cvl_1.valor IN('p')
)
for this section to be as follows:
WHERE
var.disponibilidade = 1
AND(
(ctp.codigo != 'tamanho' AND ctp_1.codigo = 'tamanho' AND cvl_1.valor IN('p'))
OR
(ctp.codigo = 'tamanho')
)
It's not possible to reference columns from the outer query from inside an inline view query.
In the MySQL venacular, the inline view query is called a "derived table". And that name makes sense, because of the way MySQL processes it. The execution plan first materializes the inline view query into a temporary(-ish) table. Once that is done, then the outer query can run, referencing the contents of the derived table.
MySQL doesn't have available the columns from the outer query at the time the inline view query runs.
It is possible to reference columns from the outer query inside a subquery that appears for example in the SELECT list, or in the WHERE clause. We call a subquery that references columns from outer query a "correlated subquery".
My Sql query takes more time to execute from mysql database server . There are number of tables are joined with sb_tblproperty table. sb_tblproperty is main table that contain more than 1,00,000 rows . most of table contain 50,000 rows.
How to optimize my sql query to fast execution. I have also used indexing.
indexing Explain - query - structure
SELECT `t1`.`propertyId`, `t1`.`projectId`,
`t1`.`furnised`, `t1`.`ownerID`, `t1`.`subType`,
`t1`.`fors`, `t1`.`size`, `t1`.`unit`,
`t1`.`bedrooms`, `t1`.`address`, `t1`.`dateConfirm`,
`t1`.`dateAdded`, `t1`.`floor`, `t1`.`priceAmount`,
`t1`.`priceRate`, `t1`.`allInclusive`, `t1`.`booking`,
`t1`.`bookingRate`, `t1`.`paidPercetage`,
`t1`.`paidAmount`, `t1`.`is_sold`, `t1`.`remarks`,
`t1`.`status`, `t1`.`confirmedStatus`, `t1`.`source`,
`t1`.`companyName` as company, `t1`.`monthly_rent`,
`t1`.`per_sqft`, `t1`.`lease_duration`,
`t1`.`lease_commencement`, `t1`.`lock_in_period`,
`t1`.`security_deposit`, `t1`.`security_amount`,
`t1`.`total_area_leased`, `t1`.`lease_escalation_amount`,
`t1`.`lease_escalation_years`, `t2`.`propertyTypeName` as
propertyTypeName, `t3`.`propertySubTypeName` subType,
`t3`.`propertySubTypeId` subTypeId, `Owner`.`ContactName`
ownerName, `Owner`.`companyName`, `Owner`.`mobile1`,
`Owner`.`otherPhoneNo`, `Owner`.`mobile2`,
`Owner`.`email`, `Owner`.`address` as caddress,
`Owner`.`contactType`, `P`.`projectName` as project,
`P`.`developerName` as developer, `c`.`name` as city,
if(t1.projectId="", group_concat( distinct( L.locality)),
group_concat( distinct(L2.locality))) as locality, `U`.`firstname`
addedBy, `U1`.`firstname` confirmedBy
FROM `sb_tblproperty` as t1
JOIN `sb_contact` Owner ON `Owner`.`id` = `t1`.`ownerID`
JOIN `tbl_city` C ON `c`.`id` = `t1`.`city`
JOIN `sb_propertytype` t2 ON `t1`.`propertyType`= `t2`.`propertyTypeId`
JOIN `sb_propertysubtype` t3 ON `t1`.`subType` =`t3`.`propertySubTypeId`
LEFT JOIN `sb_tbluser` U ON `t1`.`addedBy` = `U`.`userId`
LEFT JOIN`sb_tbluser` U1 ON `t1`.`confirmedBy` = `U1`.`userId`
LEFT JOIN `sb_tblproject` P ON `P`.`id` = `t1`.`projectId` LEFT
JOIN `sb_tblpropertylocality` PL ON `t1`.`propertyId` = `PL`.`propertyId`
LEFT JOIN `sa_localitiez` L ON `L`.`id` = `PL`.`localityId`
LEFT JOIN `sb_tblprojectlocality` PROL ON `PROL`.`projectId` = `P`.`id`
LEFT JOIN `sa_localitiez` L2 ON `L2`.`id` = `PROL`.`localityId`
LEFT JOIN `sb_tblfloor` F
ON `F`.`floorName` =`t1`.`floor`
WHERE `t1`.`is_sold` != '1' GROUP BY `t1`.`propertyId`
ORDER BY `t1`.`dateConfirm`
DESC LIMIT 1000
Please provide the EXPLAIN.
Meanwhile, try this:
SELECT ...
FROM (
SELECT propertyId
FROM sb_tblproperty
WHERE `is_sold` = 0
ORDER BY `dateConfirm` DESC
LIMIT 1000
) AS x
JOIN `sb_tblproperty` as t1 ON t1.propertyId = x.propertyId
JOIN `sb_contact` Owner ON `Owner`.`id` = `t1`.`ownerID`
JOIN `tbl_city` C ON `c`.`id` = `t1`.`city`
...
LEFT JOIN `sb_tblfloor` F ON `F`.`floorName` =`t1`.`floor`
ORDER BY `t1`.`dateConfirm` DESC -- yes, again
Together with
INDEX(is_sold, dateConfirm)
How can t1.projectId="" ? Isn't projectId the PRIMARY KEY? (This is one of many reasons for needing the SHOW CREATE TABLE.)
If my suggestion leads to "duplicate" rows (that is, multiple rows with the same propertyId), don't simply add back the GROUP BY propertyId. Instead figure out why, and avoid the need for the GROUP BY. (That is probably the performance issue.)
A likely case is the GROUP_CONCAT. A common workaround is to change from
GROUP_CONCAT( distinct( L.locality)) AS Localities,
...
LEFT JOIN `sa_localitiez` L ON `L`.`id` = `PL`.`localityId`
to
( SELECT GROUP_CONCAT(distinct locality)
FROM sa_localitiez
WHERE id = PL.localityId ) AS Localities
...
# and remove the JOIN
I'm trying to make a count within several table with JOIN, but when I made several JOINs the COUNTs got wrongly counted.
Basically I've got 4 tables, named:
predective_search
predective_to_product
predective_to_category
predective_to_manufacturer
I want to count the total number of products, categories and manufacturer which has same id in table predective_search.
Here's my code:
SELECT * ,
COUNT(pp.predictive_id) AS total_products,
COUNT(pc.predictive_id) AS total_categories,
COUNT(pm.predictive_id) AS total_manufacturers
FROM predictive_search ps
LEFT JOIN predictive_to_product pp ON (ps.predictive_id = pp.predictive_id)
LEFT JOIN predictive_to_category pu ON (ps.predictive_id = pc.predictive_id)
LEFT JOIN oc_predictive_to_manufacturer pm ON (ps.predictive_id = pm.predictive_id)
GROUP BY ps.predictive_id
Also the GROUP BY is needed I think. I'm stuck at this as I'm not getting any way to do this
SELECT
ps.*,
agg_pp.total_products,
agg_pc.total_categories,
agg_pm.total_manufacturers
FROM predictive_search ps
LEFT JOIN (
SELECT pp.predictive_id, COUNT(*) AS total_products
FROM predictive_to_product pp
GROUP BY pp.predictive_id
) agg_pp ON ps.predictive_id = agg_pp.predictive_id
LEFT JOIN (
SELECT pc.predictive_id, COUNT(*) AS total_categories
FROM predictive_to_category pc
GROUP BY pc.predictive_id
) agg_pc ON ps.predictive_id = agg_pc.predictive_id
LEFT JOIN (
SELECT pm.predictive_id, COUNT(*) AS total_manufacturers
FROM predictive_to_category pm
GROUP BY pm.predictive_id
) agg_pm ON ps.predictive_id = agg_pm.predictive_id
To begin with I have 4 tables I am dealing with.
I have a classes table that is a 1->N relationship with a sections table which also has a 1->N relationship with a lessons table.
So to put it in perpective:
Classes
Sections
Lessons
The last table is an activityLog, when the student accesses a lesson this is recorded using the following:
ActivityLog Row -> actorID (user ID), classID, sectionID, lessonID
I want to pull out the last 5 unique lessons the student has visited. I tried using both DISTINCT and GROUP BY without success.
The same records are being returned each time, not the latest classes that they have visited.
Using GROUP BY
SELECT activityLog.actorID, activityLog.activityDate,
strClasses.classID, strClasses.className,
strSections.sectionID, strSections.sectionName,
strLessons.lessonID, strLessons.lessonName
FROM activityLog
LEFT JOIN strClasses ON strClasses.classID = activityLog.classID
LEFT JOIN strSections ON strSections.sectionID = activityLog.sectionID
LEFT JOIN strLessons ON strLessons.lessonID = activityLog.lessonID
WHERE activityLog.activityTypeID = 6 AND activityLog.actorID = 3
GROUP BY activityLog.lessonID
ORDER BY activityLog.activityDate DESC
LIMIT 5
Using DISTINCT
SELECT DISTINCT activityLog.actorID,
strClasses.classID, strClasses.className,
strSections.sectionID, strSections.sectionName,
strLessons.lessonID, strLessons.lessonName
FROM activityLog
LEFT JOIN strClasses ON strClasses.classID = activityLog.classID
LEFT JOIN strSections ON strSections.sectionID = activityLog.sectionID
LEFT JOIN strLessons ON strLessons.lessonID = activityLog.lessonID
WHERE activityLog.activityTypeID = 6 AND activityLog.actorID = 3
ORDER BY activityLog.activityDate DESC
LIMIT 5
I cannot figure out why the latest records are not being displayed.
Based on your change, how does this suit you?
SELECT activityLog.actorID, activityLog.activityDate,
strClasses.classID, strClasses.className,
strSections.sectionID, strSections.sectionName,
strLessons.lessonID, strLessons.lessonName
FROM activityLog
LEFT JOIN strClasses ON strClasses.classID = activityLog.classID
LEFT JOIN strSections ON strSections.sectionID = activityLog.sectionID
LEFT JOIN strLessons ON strLessons.lessonID = activityLog.lessonID
WHERE activityLog.activityTypeID = 6 AND activityLog.actorID = 3
AND activityLog.activityDate = (SELECT MAX(activityDate) FROM activityLog AS lookup WHERE lessonID = activityLog.lessonID)
ORDER BY activityLog.activityDate DESC
LIMIT 5
Based on your description, I'm not sure why you're using LEFT JOIN, but I've left it in just in case.
Try group by like below
GROUP BY activityLog.classID,activityLog.sectionID,activityLog.lessonID
I think it will work, or just sent me create scripts for these I will create that query
Well, there's got to be a datetime in the ActivityLog I hope... so Try this:
Select s.Name, c.ClassName
From Students s
left Join On Classes c
On c.ClassId In
(Select Distinct ClassId From Classes
Where (Select Count(Distinct ClassId) From Classes ic
Join ActivityLog l On l.UserId = s.UserId
And l.ClassId = c.ClassId
Where classId = c.ClassId
And activityDateTime > l.activityDateTime)
< 5)