SQL IF statement bug - mysql

create view Com as
select C.id,
IF(A.agree = null) THEN
0
else A.agree
end if
+
IF(GA.agree = null) THEN
0
else GA.agree
end if
FROM
comments C left join AGREES A on A.id_comment=C.id left join GAGREES GA on GA.id_comment=C.id
this code has a syntax error how can i fix this?

= null doesn't mean nothing. You have to use is null

Try this :
SELECT C.id,
IFNULL(A.agree, 0) + IFNULL(GA.agre, 0)
FROM comments C
left join AGREES A on A.id_comment=C.id
left join GAGREES GA on GA.id_comment=C.id

You can't nest an if block in a query like that. If you need to implement logic like that you'd use a case statement. However, in this case you'd simply use coalesce() or isnull() in-line.
select
c.id
,isnull(a.agree,0) + isnull(ga.agree,0)
from Comments as c
left join Agrees as a
on a.id_comment = c.id
left join GAgrees ga
on ga.id_comment = c.id
... alternatively (and what you'll need for MYSQL):
select
c.id
,coalesce(a.agree,0) + coalesce(ga.agree,0)
from Comments as c
left join Agrees as a
on a.id_comment = c.id
left join GAgrees ga
on ga.id_comment = c.id

in MySQL use
ISNULL() or
IS NULL or
IFNULL

Related

copy a value from mysql query if one is empty

I am having a problem with a query that sometimes, will have an empty field returned. I have tried to use CASE and COALESCE but I am likely constructing the query incorrectly.
What I need to do in the results is, if b.user_id returns empty, to copy the value from a.useracctid into b.user_id. I hope that makes sense???
Here is my query, no matter what I have tried it errors for me.
Thank you for any idea or hints you can provide
SELECT b.user_id,a.responsetime,a.latitude,a.longitude,
a.status,a.updatetime,c.address
FROM callouts_response a
LEFT JOIN ldap_user_accounts b on a.useracctid = b.id
LEFT JOIN callouts c on a.calloutid = c.id
WHERE calloutid = :cid
Not sure how you have used COALESCE() but you can do like
SELECT COALESCE(b.user_id,a.useracctid) as somecol,
a.responsetime,
a.latitude,
a.longitude,
a.status,
a.updatetime,
c.address
FROM callouts_response a
LEFT JOIN ldap_user_accounts b on a.useracctid = b.id
LEFT JOIN callouts c on a.calloutid = c.id
WHERE a.calloutid = :cid
Try this:
SELECT IF(b.user_id IS NULL, a.useracctid, b.user_id), a.responsetime,a.latitude,a.longitude,
a.status,a.updatetime,c.address
FROM callouts_response a
LEFT JOIN ldap_user_accounts b on a.useracctid = b.id
LEFT JOIN callouts c on a.calloutid = c.id
WHERE calloutid = :cid

MySQL CASE LEFT JOINS returning NULL

I have a query with a CASE statement that determines the variable object_name this variable is derived from either the x_ambitions table or the x_trybes table. The queries below were combined so that I could keep it simple by just executing one SQL query.
I've split the SELECT statement into two so that you have a better understanding. The two queries below. Work and pull the correct object_name from the database.
The problem I'm having when I combine the two queries is that the cases 'new_join_ambition','new_created_ambition','new_liked_ambition' object_name returns NULL in the LEFT JOIN.
In the combined query, If I bring the cases: 'new_join_ambition','new_created_ambition','new_liked_ambition' above the 'new_join_trybe','new_created_trybe','new_liked_trybe' cases. The opposite happens. The trybe rows return NULL.
The two SQL queries:
A: (Retrieve Object A)
SELECT
s.id,
s.object_id,
s.type,
s.postee_id,
s.user_id,
s.text,
s.registered,
CONCAT(u.x_first_name,' ',u.x_last_name) AS postee_name,
ui.image_id AS postee_image_id,
CASE s.type
WHEN 'new_join_ambition'
OR 'new_created_ambition'
OR 'new_liked_ambition'
THEN a.name
ELSE 'a'
END AS object_name
FROM
x_share s
LEFT JOIN
x_user u ON u.id = s.postee_id
LEFT JOIN
x_user_images ui ON ui.user_id = s.postee_id
LEFT JOIN
x_ambitions a ON s.type IN ('new_join_ambition', 'new_created_ambition', 'new_liked_ambition') AND s.object_id = a.id
LEFT JOIN
x_ambition_invites ai ON s.type IN ('new_join_ambition') AND s.object_id = ai.ambition_id AND s.postee_id = ai.to
LEFT JOIN
x_ambition_likes al ON s.type IN ('new_liked_ambition') AND s.object_id = al.ambition_id AND s.postee_id = al.profile_id
LEFT JOIN
x_ambition_owner aoo ON s.type IN ('new_created_ambition') AND s.object_id = aoo.ambition_id
WHERE
s.user_id = '%s'
ORDER BY
s.registered DESC
B: (Retrieve Object B)
SELECT
s.id,
s.object_id,
s.type,
s.postee_id,
s.user_id,
s.text,
s.registered,
CONCAT(u.x_first_name,' ',u.x_last_name) AS postee_name,
ui.image_id AS postee_image_id,
CASE s.type
WHEN 'new_join_trybe'
OR 'new_created_trybe'
OR 'new_liked_trybe'
THEN t.name
ELSE 'a'
END AS object_name
FROM
x_share s
LEFT JOIN
x_user u ON u.id = s.postee_id
LEFT JOIN
x_user_images ui ON ui.user_id = s.postee_id
LEFT JOIN
x_trybes t ON s.type IN ('new_join_trybe', 'new_created_trybe', 'new_liked_trybe') AND s.object_id = t.id
LEFT JOIN
x_trybe_invites ti ON s.type IN ('new_join_trybe') AND s.object_id = ti.trybe_id AND s.postee_id = ti.to
LEFT JOIN
x_trybes_likes tl ON s.type IN ('new_liked_trybe') AND s.object_id = tl.trybe_id AND s.postee_id = tl.profile_id
LEFT JOIN
x_trybe_owner too ON s.type IN ('new_created_trybe') AND s.object_id = too.trybe_id
WHERE
s.user_id = '%s'
ORDER BY
s.registered DESC
I've ran both the queries and have captured images of the results of both queries.
Set A:
Set B:
How can I combine the two without the object_name returning NULL? If you have any questions please use the comments and I'll reply without hesitation.
Thanks in advance
I don't know about the rest of your query, but your case statement is incorrect. You have:
(CASE s.type
WHEN 'new_join_ambition' OR 'new_created_ambition' OR 'new_liked_ambition'
THEN a.name
ELSE 'a'
END) AS object_name
The ORs end up treating the values as numbers, so this is equivalent to WHEN 0 THEN . . ..
What you want is this form of the case:
(CASE WHEN s.type IN ('new_join_ambition', 'new_created_ambition', 'new_liked_ambition')
THEN a.name
ELSE 'a'
END) AS object_name

conditional mysql if inner join

is possible to do a conditional join if a field is non-null?, ie if a field is null do a join and not return a value, and if a field is not null then do a join and return a value
SELECT CASE WHEN i.id_servicio is null THEN p.nombre as proveedor, origen_incidencia.nombre as origen, relativo_a.nombre as relativo, i . * , u.nombre AS usuario ELSE p.nombre as proveedor, origen_incidencia.nombre as origen, relativo_a.nombre as relativo, i . * , u.nombre AS usuario,s.nombre
end
from incidencias i
INNER JOIN usuarios AS u ON i.id_usuarios =19 AND i.id_usuarios = u.id
case when i.id_servicio is not null then
INNER JOIN servicios s ON s.id = i.id_servicio
end
INNER JOIN relativo_a ON relativo_a.id = i.id_relativo_a
INNER JOIN origen_incidencia ON origen_incidencia.id = i.id_origen_incidencia
INNER JOIN proveedores p ON p.id = i.id_proveedor
Yes, it's called an outer join.
There are a couple of flavors of those. In this particular case you can use a left outer join, often just referred to as left join.
This query will return all incidencias and will just return NULL for the name if there is no service linked to the -erm- incident (?).
SELECT
i.id,
s.nombre
FROM incidencias i
LEFT JOIN servicios s ON s.id = i.id_servicio
There is also the right join, which does the same, but the other way around (rows in first table are optional). Quite often, using right join is considered bad practice, since it is more confusing to read, especially when you combine it with left joins in the same query. I don't think there are cases where you must use it, since you can always replace it with a left join by just reversing the tables.

MySQL / PHP - 2 different arguments for 1 table

I have the following SQL:
$queryString = "
SELECT
iR.lastModified,
d.*,
c2.title as stakeholderTitle,
u.username as authorUsername,
c.title as authorContactName,
GROUP_CONCAT(iR.stakeholderRef) AS participants
FROM
informationRelationships iR,
contacts c2
INNER JOIN
debriefs d ON
d.id = iR.linkId
LEFT JOIN
users u ON
u.id = iR.author
LEFT JOIN
contacts c ON
c.ref = u.contactId
LEFT JOIN
debriefs d2 ON
d2.stakeholder = c2.ref
WHERE
(
iR.clientRef = '$clientRef' OR
iR.contactRef = '$contactRef'
)
AND
iR.projectRef = '$projectRef' AND
iR.type = 'Debrief'
GROUP BY
iR.linkId
ORDER BY
d.dateOfEngagement
";
notice how I require 2 different bits of data for the the contacts table.
So at one point, I need to match
c.ref = u.contactId
This will return one bit of information
but I also need a completely different grouping:
d2.stakeholder = c2.ref
Problem is that the title is the column i'm interested in for both:
c2.title as stakeholderTitle,
...
c.title as authorContactName
How do I go about doing this?
My current try is returning:
Error: Unknown column 'iR.linkId' in 'on clause'
I'm not sure I really understand what is happening here:
how to join two tables on common attributes in mysql and php?
EDIT::::---ANSWERED--zerkms
$queryString = "
SELECT
iR.lastModified,
d.*,
c2.title as stakeholderTitle,
u.username as authorUsername,
c.title as authorContactName,
GROUP_CONCAT(iR.stakeholderRef) AS participants
FROM
informationRelationships iR
INNER JOIN
debriefs d ON
d.id = iR.linkId
INNER JOIN
contacts c2 ON
d.stakeholder = c2.ref
LEFT JOIN
users u ON
u.id = iR.author
LEFT JOIN
contacts c ON
c.ref = u.contactId
WHERE
(
iR.clientRef = '$clientRef' OR
iR.contactRef = '$contactRef'
)
AND
iR.projectRef = '$projectRef' AND
iR.type = 'Debrief'
GROUP BY
iR.linkId
ORDER BY
d.dateOfEngagement
";
By re-ordering my query I have managed to get both columns in... Thanks zerkms!
You cannot mix implicit joins and explicit joins in a single query in mysql.
So
FROM informationRelationships iR,
contacts c2
should be rewritten to
FROM informationRelationships iR
INNER JOIN contacts c2 ON ...
Do not use cartesian product and joins in the same query (not subquery), here, use only joins (CROSS JOIN is the same as cartesian product).

i need to do an sql with if then else to join tables if the field is not null?

i need an sql stament that will give me something like this where if a field is null it doesn't do the join
SELECT AdminID,tblapartments.NameNo, tblgarages.GarageID, tblclients.Name FROM tbladmin,tblclients,tblgarages,tblapartments WHERE tblclients.ClientID =tbladmin.ClientID AND
IF (tbladmin.ApartmentID != null)
{
tblapartments.ApartmentID = tbladmin.ApartmentID
}
AND If(tbladmin.GarageID != Null)
{
tblgarges.GarageID = tbladmin.GarageID
}
Unless I'm missing something, this should just be an outer join.
SELECT
AdminID,
tblapartments.NameNo,
tblgarages.GarageID,
tblclients.Name
FROM
tbladmin INNER JOIN tblclients ON tbladmin.ClientID = tblclients.ClientID
LEFT OUTER JOIN tblgarages ON tbladmin.GarageID = tblgarages.GarageID
LEFT OUTER JOIN tblapartments ON tbladmin.ApartmentId = tblapartments.ApartmentID
You can use LEFT JOINs, when the joined column does not exist in the other table the result is a lot of NULL fields:
SELECT AdminID,tblapartments.NameNo, tblgarages.GarageID, tblclients.Name
FROM tbladmin
INNER JOIN tblclients
ON tbladmin.ClientID = tblclients.CliendID
LEFT JOIN tblgarages
ON tbladmin.GarageID = tblgarages.GarageID
LEFT JOIN tblapartments
ON tbladmin.ApartmentID = tblapartments.ApartmentID
I do not believe that this type of if logic is SQL standard. You could possibly implement it in a procedural SQL langauge like PL/SQL, plpgsql ... however to accomplish what you after i think a left join what you should look at.
SELECT AdminID,tblapartments.NameNo, tblgarages.GarageID, tblclients.Name
FROM tbladmin a
join tblclients b on b.ClientID = a.ClientID
left join tblapartments c on c.ApartmentID = a.ApartmentID
left join tblgarges d on d.GarageID = a.GarageID