Using an IF Statement in MySQL - mysql

I have the below SQL statement. What I would like to do is include an IF statement to cover the possibility of one of the columns returning a 0 or blank result, there are no 0 ID's. In this case, I'm trying to cover the possibility of the magez_cfv_nations result possibly returning a zero or blank result.
SELECT c.clan_name, n.nation_name,
CONCAT(r.rarity_shorthand, " - ", r.rarity_name) AS rarity_text,
t.trigger_name, s.skill_name
FROM `magez_cfv_cards` AS cards
JOIN `magez_cfv_clans` c ON cards.clan_id = c.clan_id
JOIN `magez_cfv_nations` n ON cards.nation_id = n.nation_id
JOIN `magez_cfv_rarity` r ON cards.rarity_id = r.rarity_id
JOIN `magez_cfv_trigger` t ON cards.trigger_id = t.trigger_id
JOIN `magez_cfv_skills` s ON cards.skill_id = s.skill_id

You need a LEFT JOIN
The LEFT JOIN keyword returns all rows from the left table
(table_name1), even if there are no matches in the right table
Try this
SELECT c.clan_name, n.nation_name,
CONCAT(r.rarity_shorthand, " - ", r.rarity_name) AS rarity_text,
t.trigger_name, s.skill_name
FROM `magez_cfv_cards` AS cards
JOIN `magez_cfv_clans` c ON cards.clan_id = c.clan_id
LEFT JOIN `magez_cfv_nations` n ON cards.nation_id = n.nation_id
JOIN `magez_cfv_rarity` r ON cards.rarity_id = r.rarity_id
JOIN `magez_cfv_trigger` t ON cards.trigger_id = t.trigger_id
JOIN `magez_cfv_skills` s ON cards.skill_id = s.skill_id

the function you should use is IIF() and its syntax is
IIF([condition],[if true],[if false])

Related

Counting all rows in a SQL Query with multiple left joins

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"

MySql - having issues with double left join

I am having issues with getting this double left join to get the listingspecificsListPrice, but that info exists in the table, cant figure out why it would not include it. This is my sql.
SELECT mls_subject_property.*, mls_images.imagePath, mls_forms_listing_specifics.listingspecificsListPrice
FROM mls_subject_property
LEFT JOIN mls_images ON mls_subject_property.mls_listingID = mls_images.mls_listingID
LEFT JOIN mls_forms_listing_specifics ON mls_forms_listing_specifics.mls_listingID = mls_subject_property.mls_listingID AND mls_images.imgOrder = 0
WHERE userID = 413
GROUP BY mls_subject_property.mls_listingID
The result comes out like this..
All of the other fields come back, but it doesnt seem to want to bring back those two items.
This is a picture of the other table, to show that the data does in fact exist.
The mls_images.imgOrder = 0 condition should be in the join with mls_images, not mls_forms_listing_specifics.
Don't use GROUP BY if you're not using any aggregation functions. Use SELECT DISTINCT to prevent duplicates.
SELECT DISTINCT mls_subject_property.*, mls_images.imagePath, mls_forms_listing_specifics.listingspecificsListPrice
FROM mls_subject_property
LEFT JOIN mls_images ON mls_subject_property.mls_listingID = mls_images.mls_listingID AND mls_images.imgOrder = 0
LEFT JOIN mls_forms_listing_specifics ON mls_forms_listing_specifics.mls_listingID = mls_subject_property.mls_listingID
WHERE userID = 413

Delete from two or more tables

lets says i have these variable:
$post_id = 222;
$IsLoggIn =2;
I have same column "post_id" name in five different tables.
I want to write an sql statement to check and see if there is a row with column name "post_id" whose value is equal to variable "$post_id" and delete that row
Note: Apart from the "public_feed_table", it is possible there could be no row with post_id equal to variable "$post_id" so the sql statement should check if there is a row before deleting.
I want a single sql statement that can do this job.
What I tried is below. Please help:
global $dbc_conn,
$public_feed_table,
$images_table,
$comments_table,
$rating_table,
$notification_table,
$IsLoggIn;
$sql = "DELETE
p,i,c,r,n
FROM
$public_feed_table p
LEFT JOIN
$images_table i,
$comments_table c,
$rating_table r,
$notification_table n
ON
i.post_id,
c.post_id,
r.post_id,
n.post_id=p.post_id
WHERE p.post_id='$post_id'
AND p.user_id='$IsLoggIn'
";
//query database
$query = mysqli_query($dbc_conn,$sql);
You join Syntax is worng. It must be:
$sql = "DELETE p,i,c,r,n
FROM
$public_feed_table p
LEFT JOIN
$images_table i ON
p.post_id = i.post_id
LEFT JOIN
$comments_table c ON
p.post_id = c.post_id
LEFT JOIN
$rating_table r ON
p.post_id = r.post_id
LEFT JOIN
$notification_table n ON
p.post_id=n.post_id
WHERE p.post_id='$post_id'
AND p.user_id='$IsLoggIn'
";
For more Information see: http://www.w3schools.com/sql/sql_join_left.asp
Your JOIN syntax is total weird. It rather should be
FROM
$public_feed_table p
LEFT JOIN
$images_table i ON i.col = p.col,
LEFT JOIN $comments_table c ON p.col = c.col,
** col is for example, substitute it with actual column name per your table schema

MySQL join only on row existing

I have the following query
SELECT custconcompany, custconfirstname, custconlastname, custconemail, custconphone, shipaddress1, shipaddress2, shipcity, stateabbrv, shipzip, countryname, websitecheck.formfieldfieldvalue websitevalue, excludecheck.formfieldfieldvalue excludevalue
FROM obcisc_customers
JOIN ( (obcisc_shipping_addresses JOIN obcisc_countries
ON obcisc_shipping_addresses.shipcountryid = obcisc_countries.countryid)
LEFT JOIN obcisc_country_states
ON obcisc_shipping_addresses.shipstateid = obcisc_country_states.stateid
LEFT JOIN obcisc_formfieldsessions websitecheck
ON obcisc_shipping_addresses.shipformsessionid = websitecheck.formfieldsessioniformsessionid
LEFT JOIN obcisc_formfieldsessions excludecheck
ON obcisc_shipping_addresses.shipformsessionid = excludecheck.formfieldsessioniformsessionid)
ON obcisc_customers.customerid = obcisc_shipping_addresses.shipcustomerid
WHERE custgroupid = 11
AND websitecheck.formfieldfieldid = 24
AND excludecheck.formfieldfieldid = 30
AND excludecheck.formfieldfieldvalue != 'a:1:{i:0;s:3:"Yes";}'
ORDER BY shipstate, shipcity
This works great except I also need it to return rows where "excludecheck.formfieldfieldid=30" does not exist... right now it's not returning them
When writing a LEFT JOIN, any criteria on the table you're joining with should be put into the ON clause. If you put it into the WHERE clause, you'll filter out the results in the first table that don't have a matching row in the second table, because the NULL value that comes from the outer join will not match the criteria.
SELECT custconcompany, custconfirstname, custconlastname, custconemail, custconphone, shipaddress1, shipaddress2, shipcity, stateabbrv, shipzip, countryname, websitecheck.formfieldfieldvalue websitevalue, excludecheck.formfieldfieldvalue excludevalue
FROM obcisc_customers
JOIN obcisc_shipping_addresses
ON obcisc_customers.customerid = obcisc_shipping_addresses.shipcustomerid
JOIN obcisc_countries
ON obcisc_shipping_addresses.shipcountryid = obcisc_countries.countryid)
LEFT JOIN obcisc_country_states
ON obcisc_shipping_addresses.shipstateid = obcisc_country_states.stateid
LEFT JOIN obcisc_formfieldsessions websitecheck
ON obcisc_shipping_addresses.shipformsessionid = websitecheck.formfieldsessioniformsessionid
AND websitecheck.formfieldfieldid = 24
LEFT JOIN obcisc_formfieldsessions excludecheck
ON obcisc_shipping_addresses.shipformsessionid = excludecheck.formfieldsessioniformsessionid
AND excludecheck.formfieldfieldid = 30
AND excludecheck.formfieldfieldvalue != 'a:1:{i:0;s:3:"Yes";}')
WHERE custgroupid = 11
ORDER BY shipstate, shipcity
Another way to do it is by putting (excludecheck.formfieldfieldid = 30 OR excludecheck.formfieldfieldid IS NULL) in the WHERE clause. But this is more verbose and also I believe it's harder for MySQL to optimize, especially if you have several tables you're joining like this.

Convert this SQL to HQL? (left join with values instead of columns)

I'm trying to convert this SQL to HQL, but I found no way to do that left join.
SELECT
mdcs_causa.id_causa,
usuarios.ds_usuario,
usuarios.setor,
empresas.ds_empresa,
itens_controle.id_item_controle,
itens_controle.ds_item,
itens_controle.ds_indicador,
itens_controle.ds_cliente,
itens_controle.desdobramento,
itens_controle.auxiliar,
itens_controle.bmk_nome,
itens_controle.bmk_vlr,
m.status,
m.medido,
m.medicao,
m.fca,
m.am_cronico,
m.ac_cronico,
m.ap_cronico,
m.id_medicoes as idmedicao,
itens_controle.prioridade
FROM
mdcs
INNER JOIN mdcs_causa
ON mdcs.id_mdc = mdcs_causa.id_mdc
INNER JOIN itens_controle
ON mdcs_causa.Id_Item_Controle = itens_controle.id_item_controle
INNER JOIN usuarios
ON usuarios.id_usuario = itens_controle.id_usuario
INNER JOIN empresas
ON empresas.id_empresa = usuarios.id_cliente_tabela
LEFT JOIN medicoes m
ON (
itens_controle.id_item_controle = m.id_item_controle
and
m.nm_ano = 2013
and
m.nm_periodo = 2
and
mdcs_causa.id_mdc = mdcs.id_mdc
)
WHERE
mdcs.id_mdc = 5077
I thought I could put the nm_ano and nm_periodo conditions in the where clause, with an OR to m.id_item_controle is null but this OR condition didn't seem to work, even in SQL.
Another approach was to left join a sub query. That worked in SQL, but I think HQL doesn't support that.
It can be done with with keyword:
...
left join itens_controle.medicoes m with (m.nm_ano = 2013 and m.nm_periodo = 2 and mdcs_causa.id_mdc = mdcs.id_mdc)
where mdcs.id_mdc = 5077
Instead of explicit values you should supply them as arguments.
Read this in this pdf left join is used
as below:
Query getEBills =session.createQuery( session.createQuery( from " EBill ebill EBill
ebill
left join ebill.accountTransaction where
ebill.balance > 500";
Li li f l bi i li () ist listOfRowValues = getDebitTransactions.list();
for (Object[] singleRowValues : listOfRowValues) {
// pull off the EBill // pull off the EBill
EBill ebill = (EBill)singleRowValues[0];
I dont have any experience in HQL, i have pasted what i have found for you. hope this will help you in any way.