Mysql multiple tables left join last table - mysql

I have checked several threads on here and cannot find the answer to my question....
I am trying to do a mysql query with multiple tables and left join the last table. It does not like the left join and gives me no results when I include it. Any help is greatly appreciated :)
(I am using Joomla)
query = "SELECT DISTINCT u.id as uid, CONCAT(u.first_name,' ',u.last_name) as name1,
u.grad as grad, u.opt_out as opt_out
FROM #__bl_teams as t, #__bl_regions as r, #__users as u
LEFT JOIN #__bl_paid as pd ON pd.u_id = u.id
WHERE u.team_id = t.id AND u.team_id != '' AND u.s_id = $sid
AND ((t.id = $tid)OR($tid=0)) AND (t.id IN ($teamsfull))
AND ( (t.id IN(".$tc_teams."))OR(".$tc_id." = 0))
AND ((r.id = ".$mid.")OR(".$mid." = 0))
AND ((r.s_id = ".$sid.")OR(".$mid." = 0))
AND ( (FIND_IN_SET(t.id,r.teams) )OR(".$mid." = 0) )
AND u.id NOT IN($paidrows) AND u.id NOT IN ($rsrows) GROUP BY u.id";
$db->setQuery($query, $pageNav->limitstart, $pageNav->limit);
$rows50 = $db->loadObjectList();

You are mixing old-style joins and new style joins. That is your problem. The table aliases aren't recognized throughout the from statement, the way you expect them to be. Buried in the documentation is this warning:
However, the precedence of the comma operator is less than of INNER
JOIN, CROSS JOIN, LEFT JOIN, and so on. If you mix comma joins with
the other join types when there is a join condition, an error of the
form Unknown column 'col_name' in 'on clause' may occur. Information
about dealing with this problem is given later in this section.
Simple rule: Never use commas in the from clause.
So, rewrite your query using explicit joins and that will fix the problem.

I don't know the ctual tables, but this query is too long and will have unexpected results results. Anyways, Left join the other tables too.
query = "SELECT DISTINCT u.id as uid, CONCAT(u.first_name,' ',u.last_name) as name1,
u.grad as grad, u.opt_out as opt_out
FROM #__users as u
LEFT JOIN #__bl_paid as pd ON pd.u_id = u.id
LEFT JOIN #__bl_teams as t ON t.u_id = u.id
LEFT JOIN #__bl_regions as r ON r.u_id = u.id
WHERE u.team_id != ''
AND u.s_id = $sid
AND ((t.id = $tid)
OR($tid=0))
AND (t.id IN ($teamsfull))
AND ( (t.id IN(".$tc_teams."))
OR(".$tc_id." = 0))
AND ((r.id = ".$mid.")
OR(".$mid." = 0))
AND ((r.s_id = ".$sid.")
OR(".$mid." = 0))
AND ( (FIND_IN_SET(t.id,r.teams) )
OR(".$mid." = 0) )
AND u.id NOT IN($paidrows)
AND u.id NOT IN ($rsrows)
GROUP BY u.id";

Related

MySQL Where Statement While checking value

$sql = "SELECT cc.name AS c_name, ev.name AS event_name, ev.eventModeId AS event_mode, ev.carClassHash, cc.carClassHash
FROM EVENT_DATA e
INNER JOIN PERSONA p ON e.personaId = p.ID
INNER JOIN CUSTOMCAR cc ON cc.ownedCarId = e.carId
INNER JOIN CAR_CLASSES ccs ON ccs.store_name = cc.name
INNER JOIN USER u ON u.ID = p.USERID
LEFT JOIN BAN b ON b.user_id = u.ID
INNER JOIN EVENT ev ON ev.ID = e.EVENTID
WHERE (p.name = ?
AND ev.carClassHash = cc.carClassHash)";
This query works for me except I'd also like to display any carClassHash with the value '607077938'. Is there a way I could somehow keep the above query to check if the event hash matches the car class hash but also still display values where the carClassHash (cc.carClassHash) is equal to '607077938'?
Thanks! :)
Why not use OR in the WHERE clause?
[...]
WHERE ((p.name = ? AND ev.carClassHash = cc.carClassHash) OR (cc.carClassHash = 607077938))
This should work if that value is an integer. If it's a string, use quotes around it.

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

Convert SQL query to Rails ActiveRecord query

I have an sql query with multiple left joins that works fine:
query = <<-eos
select date(t.completed_at) completed_date, s.id district, assignee_id, u.first_name, u.last_name, count(t.id) completed_tasks
from tasks t
left join tickets k on k.id = t.ticket_id
left join installations i on i.id = k.installation_id
left join administrative_areas a on i.ward_id = a.id
left join service_areas s on s.id = a.service_district_id
left join users u on u.id = t.assignee_id
where 1 = 1
and s.id = '#{district_id}'
and t.status = '#{status}'
and t.kind = 1
and t.completed_at >= '#{days_ago.days.ago.beginning_of_day.to_s(:db)}'
and t.completed_at <= '#{days_until.days.ago.beginning_of_day.to_s(:db)}'
group by date(t.completed_at), s.id, s.name, u.first_name, u.last_name, t.assignee_id
eos
I got this value after mapping: [{:completed_date=>"2015-07-11", :district=>"1339", :assignee_id=>"215371", :assignee_name=>nil, :first_name=>"John_9", :last_name=>"Ant", :completed_tasks=>"1"}] for the sql query.
But I want to stop using the sql query and switch to ActiveRecord query and I have it converted to ActiveRecord like this:
Task.joins("LEFT JOIN tickets k ON k.id = tasks.ticket_id").
joins("LEFT JOIN installations i ON i.id = k.installation_id").
joins("LEFT JOIN administrative_areas a ON i.ward_id = a.id").
joins("LEFT JOIN service_areas s ON s.id = a.service_district_id").
joins("LEFT JOIN users u ON u.id = tasks.assignee_id").
where(["s.id = ? and tasks.status = ? and tasks.kind = ? and tasks.completed_at >= ? and tasks.completed_at <= ?", 26, "#{status}", 1, "#{days_ago.days.ago.beginning_of_day.to_s(:db)}", "#{days_until.days.ago.beginning_of_day.to_s(:db)}"]).
select('date(tasks.completed_at) as completed_date, s.id as district, assignee_id, u.first_name, u.last_name, count(tasks.id) as completed_tasks').
group("date(tasks.completed_at), s.id, s.name, u.first_name, u.last_name, tasks.assignee_id")
But the problem I have here is trying to do a select from multiple columns in different tables, the only value that the ActiveRecord query returns belong to the task table alone. I don't know what am doing wrong, maybe it's the left joins or the select
[#<Task status: 1, assignee_id: 215356, kind: 1>]
Please, how do I convert the above sql query to ActiveRecord query and get the same result?
You can use Scuttle.io the first result is always terrible, but try to configure associations in second tab. And please try to avoid constructions like this:
where("params.id = #{param[:id]}")
it is unsecured (sql injection)!

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).

SQL returns incorrect data using 2 left joins

I have written a MYSQL script, that returns incorrect data. I am quite fluent in SQL, but this query is not returning correct results. Can someone have a look and see whats going on. The problem is the noOfBids, and noOfRatedTimes. The values are the same for both columns and are large values too.
select
a.user_name as userName,
coalesce(count(b.sp_user_name),0) as noOfBids,
coalesce(ROUND(AVG(b.a_amount),2),0) as avgAmount,
coalesce(count(d.sp_user_name),0) as noOfRatedTimes,
coalesce(ROUND(AVG(d.user_rate),2),0)
from users a
left join project_imds b
on b.sp_user_name = a.user_name
left join projects c
on b.project_code = c.project_code
left join sp_user_rating d
on d.sp_user_name = b.sp_user_name
where a.user_type = 'SP'
and a.active = 'Y'
group by a.user_name
order by coalesce(ROUND(AVG(d.user_rate),2),0) desc;
I have created a workaround on this, by creating a temp table to get the avg values and joining this to the main query.
Since I don't know the specifics of the data behind your query, this is only a guess. But perhaps you'd rather join "sp_user_rating" directly to "users", changing
left join sp_user_rating d
on d.sp_user_name = b.sp_user_name
to
left join sp_user_rating d
on d.sp_user_name = a.user_name
select
a.user_name as userName,
coalesce(count(b.sp_user_name),0) as noOfBids,
coalesce(ROUND(AVG(b.a_amount),2),0) as avgAmount,
coalesce(count(d.sp_user_name),0) as noOfRatedTimes,
coalesce(ROUND(AVG(d.user_rate),2),0)
from users as a
left join project_imds as b
on b.sp_user_name = a.user_name
left join projects as c
on b.project_code = c.project_code
left join sp_user_rating as d
on d.sp_user_name = b.sp_user_name
where a.user_type = 'SP'
and a.active = 'Y'
group by a.user_name
order by coalesce(ROUND(AVG(d.user_rate),2),0) desc;