Where clause using alias column with IF and IFNULL - mysql

I have an mysql query like below:
SELECT
sppt_ticket.*,
IF(sppt_read_support_ticket.ID_aks_user IS NULL,'N', 'Y') AS `read_status`,
IFNULL(readcomment.total_comment, 0) AS unread_comment
FROM
sppt_ticket
LEFT JOIN
sppt_read_support_ticket ON
sppt_ticket.ID_support_ticket = sppt_read_support_ticket.ID_support_ticket AND
ID_aks_user = 1
LEFT JOIN
(SELECT
sppt_comment.ID_support_ticket, SUM(IF(sppt_read_comment.ID_aks_user IS NULL, 1, 0))
AS
total_comment
FROM
sppt_comment
LEFT JOIN
sppt_read_comment
ON
sppt_comment.ID_comment = sppt_read_comment.ID_comment
AND
sppt_read_comment.ID_aks_user = 1
GROUP BY
sppt_comment.ID_support_ticket) AS readcomment ON readcomment.ID_support_ticket = sppt_ticket.ID_support_ticket
What I want to get in where clause is like this
WHERE read_status = 'Y'
I've tried using subquery, but still I didn't get it..
any help?

Have you tried this:
SELECT * FROM
(
-- your original query as a table
SELECT
sppt_ticket.*,
IF(sppt_read_support_ticket.ID_aks_user IS NULL,'N', 'Y') AS `read_status`,
IFNULL(readcomment.total_comment, 0) AS unread_comment
FROM
sppt_ticket
LEFT JOIN
sppt_read_support_ticket ON
sppt_ticket.ID_support_ticket = sppt_read_support_ticket.ID_support_ticket AND
ID_aks_user = 1
LEFT JOIN
(SELECT
sppt_comment.ID_support_ticket, SUM(IF(sppt_read_comment.ID_aks_user IS NULL, 1, 0))
AS
total_comment
FROM
sppt_comment
LEFT JOIN
sppt_read_comment
ON
sppt_comment.ID_comment = sppt_read_comment.ID_comment
AND
sppt_read_comment.ID_aks_user = 1
GROUP BY
sppt_comment.ID_support_ticket) AS readcomment ON readcomment.ID_support_ticket = sppt_ticket.ID_support_ticket
)
as temptable
where read_status = 'Y' -- this should work
Or you can use HAVING instead of WHERE if you do not want to treat your query as a table:
SELECT
sppt_ticket.*,
IF(sppt_read_support_ticket.ID_aks_user IS NULL,'N', 'Y') AS `read_status`,
IFNULL(readcomment.total_comment, 0) AS unread_comment
FROM
sppt_ticket
LEFT JOIN
sppt_read_support_ticket ON
sppt_ticket.ID_support_ticket = sppt_read_support_ticket.ID_support_ticket AND
ID_aks_user = 1
LEFT JOIN
(SELECT
sppt_comment.ID_support_ticket, SUM(IF(sppt_read_comment.ID_aks_user IS NULL, 1, 0))
AS
total_comment
FROM
sppt_comment
LEFT JOIN
sppt_read_comment
ON
sppt_comment.ID_comment = sppt_read_comment.ID_comment
AND
sppt_read_comment.ID_aks_user = 1
GROUP BY
sppt_comment.ID_support_ticket) AS readcomment ON readcomment.ID_support_ticket = sppt_ticket.ID_support_ticket
HAVING read_status = 'Y' -- use HAVING instead of WHERE
The reason why treating your original query as a table works is because of the way values are evaluated in the query. In your original query, the alias read_status cannot be used with the WHERE clause because the actual value might not yet be known when the WHERE clause is evaluated. As documented in Section B.1.5.4, “Problems with Column Aliases”. Treating it as a table ensures that the value for read_status has already been evaluated.
For the HAVING approach, MySQL created an extension to standard SQL that permits references in the HAVING clause to aliased expressions in the select list.

Related

SQL left join exclude non matching records

I'm working on this query (running on MySQL 5.6):
SELECT
veicoli_contratti.targa AS targa,
veicoli_contratti.canone_noleggio AS canone,
anag_convenzionati.nome AS convenzionato,
SUM(noleggio_veicoli.fatt_prezzo_totale_noleggio) AS noleggi_incasso,
noleggio_veicoli.modalita_noleggio,
COUNT(DISTINCT noleggio_veicoli.id) AS noleggi
FROM
veicoli_contratti
LEFT JOIN
noleggio_veicoli ON veicoli_contratti.id = noleggio_veicoli.id_veicolo
INNER JOIN
anag_convenzionati ON veicoli_contratti.id_convenzionato = anag_convenzionati.id
WHERE
(veicoli_contratti.data_cancellazione IS NULL)
AND (veicoli_contratti.targa <> '')
AND (noleggio_veicoli.data_cancellazione IS NULL)
AND (anag_convenzionati.data_cancellazione IS NULL)
AND (YEAR(noleggio_veicoli.rientro_data) = 2020)
AND (MONTH(noleggio_veicoli.rientro_data) = 10)
AND ((noleggio_veicoli.stato_noleggio = 'C')
OR (noleggio_veicoli.stato_noleggio = 'F')
)
AND ((noleggio_veicoli.modalita_noleggio = 'S')
OR (noleggio_veicoli.modalita_noleggio = 'OPO')
OR (noleggio_veicoli.modalita_noleggio = 'M')
)
AND (veicoli_contratti.stato = 'OPERATIVA')
GROUP BY anag_convenzionati.id , veicoli_contratti.id , noleggio_veicoli.modalita_noleggio
ORDER BY convenzionato , noleggi DESC , canone DESC , noleggi_incasso DESC ;
I thought LEFT JOIN clause will produce a record even if there's not a matching record in table noleggio_veicoli but this doesn't happen.
The result include just records where a match is found between veicoli_contratti and noleggio_veicoli.
I tried also adding OR noleggio_veicoli.id IS NULL in WHERE clause but it's not the solution.
How can I fix this?
I created an SQL fiddle to try this here
Your understand is correct. However, the where clause is "undoing" the LEFT JOIN. Why?
You have conditions such as this:
AND ((noleggio_veicoli.stato_noleggio = 'C') OR (noleggio_veicoli.stato_noleggio = 'F'))
Well, NULL fails those conditions so non-matches are filtered out. This condition (along with other conditions) should be included in the ON clause. For this one, it looks like:
AND noleggio_veicoli.stato_noleggio IN ('C', 'F')

Adding a WHERE condition on an IF alias in a MySQL query

I'm having trouble adding a condition on aliases is_paid, is_overdue and is_outstanding in the following query:
SELECT r.doc_number,
r.doc_date,
r.due_date,
r.currency,
r.amount,
r.vat,
r.vatammount,
(r.amount + r.vatammount) final_amount,
r.currency,
b.boq_id,
b.boq_comp_id,
b.boq_client_id,
b.boq_agency,
b.boq_date,
b.boq_orders,
b.receivable_id,
c.comp_name,
crm.`cn-name-first`,
crm.`cn-name-last`,
bi.inv_path,
(SELECT SUM(amount_recieved)
FROM receivables_payments
WHERE r_id = b.receivable_id) total_amount_received,
IF (r.amount + r.vatammount =
(SELECT SUM(amount_recieved)
FROM receivables_payments
WHERE r_id = b.receivable_id),
'1',
'0') AS is_paid,
IF (CURRENT_DATE >= r.due_date
AND r.amount + r.vatammount !=
(SELECT SUM(amount_recieved)
FROM receivables_payments
WHERE r_id = b.receivable_id),
'1',
'0') AS is_overdue,
IF (r.due_date < CURRENT_DATE
AND r.amount + r.vatammount !=
(SELECT SUM(amount_recieved)
FROM receivables_payments
WHERE r_id = b.receivable_id),
'1',
'0') AS is_outstanding
FROM receivables r
LEFT JOIN boq b ON b.receivable_id = r.id
LEFT JOIN boq_invoices bi ON bi.inv_boq_id = b.boq_id
LEFT JOIN comp_companies c ON c.comp_id = b.boq_comp_id
LEFT JOIN crm_contacts crm ON crm.contact_id = b.boq_client_id
WHERE r.status = 'active'
AND r.doc_type = 'inv'
AND b.boq_status = 'active'
AND is_paid = '1'
ORDER BY r.doc_date DESC LIMIT 10
Is there any way to modify this query and to make it possible to add a condition on those three aliases?
use alias in where condition .. is not allowed . because .is not possibile
the query code is evaluted based on a specified order .. starting from FROM then
WHERE clause and last the SELECT and the column alias so .. when the where is performed the column alias is not available at the query
You could try with an having condition because having work on the result of the query and not on the raw rows value .. (this could have effect on performance ..because all the query is performed and only the result is filtered by having)

How to query mysql to select and group by multiple values

I'm trying to select and group by all the contentid values of the table below where the match criteria can be several different values.
the contentid values actually represent cars, so I need to select [and group by] all the contentis where the values are 'GMC' and the values are 'sedan' and the value is 'automatic.
i.e. I'm trying to select all the GMC sedans with an automatic transmission.
a query like this fails [obviously]:
select * from modx_site_tmplvar_contentvalues WHERE
`value` = 'gmc' and
`value` = 'tacoma'
group by contentid
I have no idea how to create a query like that. Any suggestions?
You need to "pivot" these data on "tmplvarid", but unfortunately for you MySQL doesn't have a PIVOT statement like other RDBMS. However, you can pivot it yourself by joining in the table multiple times for each variable you care about:
SELECT
contents.contentid,
transmission.value as transmission,
type.value as type,
make.value as make
FROM
(SELECT DISTINCT contentid FROM modx_site_tmplvar_contentvalues) AS contents
LEFT JOIN
modx_site_tmplvar_contentvalues AS transmission
ON contents.contentid = transmission.contentid
AND transmission.tmplvarid = 33 -- id for transmission
LEFT JOIN
modx_site_tmplvar_contentvalues AS make
ON contents.contentid = make.contentid
AND make.tmplvarid = 13 -- id for make
LEFT JOIN
modx_site_tmplvar_contentvalues AS type
ON contents.contentid = type.contentid
AND type.tmplvarid = 17 -- id for type
WHERE
type.value = 'sedan'
AND make.value = 'GMC'
AND transmission.value = 'automatic'
You can expand this with additional joins for other criteria such as year (id 15) or mileage (id 16).
If you need to use the value only, you could try:
SELECT DISTINCT
contents.contentid,
transmission.value as transmission,
type.value as type,
make.value as make
FROM
(SELECT DISTINCT contentid FROM modx_site_tmplvar_contentvalues) AS contents
INNER JOIN
modx_site_tmplvar_contentvalues AS transmission
ON contents.contentid = transmission.contentid
AND transmission.value = 'automatic'
INNER JOIN
modx_site_tmplvar_contentvalues AS make
ON contents.contentid = make.contentid
AND make.value = 'GMC'
INNER JOIN
modx_site_tmplvar_contentvalues AS type
ON contents.contentid = type.contentid
AND type.value = 'sedan'
In any case, make sure you have an index on the value column; these queries are going to get slow.
please try this:
SELECT *
FROM modx_site_tmplvar_contentvalues t1 INNER JOIN modx_site_tmplvar_contentvalues t2 ON t1.contentid = t2.content_id
WHERE
t1.`value` = 'gmc'
AND t2.`value` = 'tacoma';
You can do this with a group by. This is the most flexible in terms of expressing the conditions. In MySQL, multiple joins will often perform better:
select contentid
from modx_site_tmplvar_contentvalues
group by contentid
having sum(`value` = 'gmc') > 0 and
sum(`value` = 'tacoma') > 0;
This is always false:
`value` = 'gmc' and
`value` = 'tacoma'
Instead, use OR:
`value` = 'gmc' OR
`value` = 'tacoma'
In a condition "and" means "this and this is true at the same time". If you want all foos and all bars, then your condition is "foo OR bar".
EDIT:
To select groups containing your values, you can write subqueries:
SELECT DISTINCT name FROM table WHERE name IN (SELECT name FROM table WHERE value='value1') AND name IN (SELECT name FROM table WHERE value='value2')

Mysql Distinct select with replace

I have the following mySql select statement it returns the below result and battling to get the result I am after.
select `tvshow`.`idShow` AS `idShow`,`tvshow`.`c00` AS `ShowName`,
if(count(distinct `episode`.`c12`),
count(distinct `episode`.`c12`),0) AS `TotalSeasons`,
if(count(`episode`.`c12`),count(`episode`.`c12`),0) AS `TotalEpisodeCount`
from
((((`tvshow`
left join `tvshowlinkpath` ON ((`tvshowlinkpath`.`idShow` = `tvshow`.`idShow`)))
left join `path` ON ((`path`.`idPath` = `tvshowlinkpath`.`idPath`)))
left join `episode` ON ((`episode`.`idShow` = `tvshow`.`idShow`)))
left join `files` ON ((`files`.`idFile` = `episode`.`idFile`)))
group by `tvshow`.`idShow`
having (count(`episode`.`c12`) > 0)
Select Result
I am trying to get a 4th column that would have the seasons listed in it e.g "Season 1,Season 2,Season 3"
I can get the the data I need by running the following select
select distinct c12 from episode where idShow = 1
It returns the following.
So i thought I could use the replace to change the results to read "Season1" but not sure how to get it to just return one string containing "Seasin1,Season2,Season3" and then add it to the select statement at the top of the view and bring it all together?
The Result I am trying to get(used Photoshop for this just so you could get the idea)
Just add GROUP_CONCAT(episode.c12) as additional column:
select `tvshow`.`idShow` AS `idShow`,`tvshow`.`c00` AS `ShowName`,
if(count(distinct `episode`.`c12`),
count(distinct `episode`.`c12`),0) AS `TotalSeasons`,
if(count(`episode`.`c12`),count(`episode`.`c12`),0) AS `TotalEpisodeCount`,
`GROUP_CONCAT(episode.c12)` as `Seasons`
from
((((`tvshow`
left join `tvshowlinkpath` ON ((`tvshowlinkpath`.`idShow` = `tvshow`.`idShow`)))
left join `path` ON ((`path`.`idPath` = `tvshowlinkpath`.`idPath`)))
left join `episode` ON ((`episode`.`idShow` = `tvshow`.`idShow`)))
left join `files` ON ((`files`.`idFile` = `episode`.`idFile`)))
group by `tvshow`.`idShow`
having (count(`episode`.`c12`) > 0)
See http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat for the documentation of this MySQL specific function.

Replace Default Null Values Returned From Left Outer Join

I have a Microsoft SQL Server 2008 query that returns data from three tables using a left outer join. Many times, there is no data in the second and third tables and so I get a null which I think is the default for left outer join. Is there a way to replace the default values in the select statement? I have a workaround in that I can select into a table variable but it feels a little dirty.
SELECT iar.Description, iai.Quantity, iai.Quantity * rpl.RegularPrice as 'Retail',
iar.Compliance FROM InventoryAdjustmentReason iar
LEFT OUTER JOIN InventoryAdjustmentItem iai on (iar.Id = iai.InventoryAdjustmentReasonId)
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'
I would like the Quantity and RegularPrice to default to zero if possible.
That's as easy as
IsNull(FieldName, 0)
Or more completely:
SELECT iar.Description,
ISNULL(iai.Quantity,0) as Quantity,
ISNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail',
iar.Compliance
FROM InventoryAdjustmentReason iar
LEFT OUTER JOIN InventoryAdjustmentItem iai on (iar.Id = iai.InventoryAdjustmentReasonId)
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'
In case of MySQL or SQLite the correct keyword is IFNULL (not ISNULL).
SELECT iar.Description,
IFNULL(iai.Quantity,0) as Quantity,
IFNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail',
iar.Compliance
FROM InventoryAdjustmentReason iar
LEFT OUTER JOIN InventoryAdjustmentItem iai on (iar.Id = iai.InventoryAdjustmentReasonId)
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'
MySQL
COALESCE(field, 'default')
For example:
SELECT
t.id,
COALESCE(d.field, 'default')
FROM
test t
LEFT JOIN
detail d ON t.id = d.item
Also, you can use multiple columns to check their NULL by COALESCE function.
For example:
mysql> SELECT COALESCE(NULL, 1, NULL);
-> 1
mysql> SELECT COALESCE(0, 1, NULL);
-> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
-> NULL
For Oracle you can use:
NVL(columnName,deafultValue) :- NVL is used to convert a null value to a default value in the query output. eg. If you want to replace null values with 'NA' then use something like this.
SELECT NVL(columnName,'NA') FROM tableName