Left Join, Order by, MySQL Optimization - sql

I have a query like this:
SELECT m...., a...., r....
FROM 0_member AS m
LEFT JOIN 0_area AS a ON a.user_id = (SELECT user_id
FROM `0_area`
WHERE user_id = m.id
ORDER BY sec_id ASC LIMIT 1)
LEFT JOIN 0_rank as r ON a.rank_id = r.id
WHERE m.login_userid = '$username'
The idea is to get the first row from 0_area table and hence the attempted inner join. However, it is not working as expected.
Between 0_area and 0_member, 0_member.id = 0_area.user_id. However, there are multiple rows of 0_area.user_id and I want the row having the lowest value of sec_id.
Any help please?

SELECT m...., a...., r....
FROM 0_member AS m
LEFT JOIN (SELECT user_id, min(sec_id) minsec
FROM `0_area`
GROUP BY user_id) g1 on g1.user_id=m.id
LEFT JOIN 0_area AS a ON a.user_id = g1.user_id and a.sec_id=minsec
LEFT JOIN 0_rank as r ON a.rank_id = r.id
WHERE m.login_userid = '$username'

Related

SQL Multiple Joins not working as expected

I have following query not working when I try to join all 4 tables (It is taking over an hour to run, I have to eventually kill the query without any data being returned).
It works when Table 1,2 & 3 are joined AND Then If I try Table 1,2 & 4 join but not when I attempt to join all 4 tables below.
Select * From
(Select
R.ID, R.MId, R.RId, R.F_Name, R.F_Value, FE.FullEval, M.Name, RC.CC
FROM Table1 as R
Inner Join Table2 FE
ON R.ID = FE.RClId and R.MId = FE.MId and R.RId = FE.RId
Inner Join Table3 as M
ON R.MId = M.MId and FE.MId = M.MId
Inner Join Table4 as RC
ON R.RId = RC.RId and FE.RId = RC.RId and FE.Date = RC.Date
) AS a
NOTE:
1) RId is not available in table3.
2) MId is not available in table4.
Thanks for help.
Since you mentioned that you don't have permission to view the query plan, try breaking down into each table join. You can also check which table join is taking time to retrieve records. From there, you can investigate the data why it's taking time. It may be because of non-availability of column keys in Table 3 and Table 4?
WITH Tab1_2 AS
(SELECT r.ID, r.MId, r.RId, r.F_Name, r.F_Value, fe.FullEval, fe.date
FROM Table1 as r
INNER JOIN Table2 fe
ON r.ID = fe.RClId
AND r.MId = fe.MId
AND r.RId = fe.RId
WHERE ... -- place your conditions if any
),
Tab12_3 AS
(SELECT t12.*, m.Name
FROM Tab1_2 t12
INNER JOIN Table3 as m
ON t12.MId = m.MId
WHERE ... -- place your conditions if any
),
Tab123_4 AS
(SELECT t123.ID, t123.MId, t123.RId, t123.F_Name, t123.F_Value, t123.FullEval, rc.CC
FROM Tab12_3 t123
INNER JOIN Table4 as rc
ON t123.RId = rc.RId
AND t123.Date = rc.Date
WHERE ... -- place your conditions if any
)
SELECT *
FROM Tab123_4 t1234

SQL Server Query returning duplicate rows

I have a query of SQL that is a join of multiple tables, it is returning duplicate rows and after hours of going through it can't find out where its going wrong
SELECT
StkItem.iUOMStockingUnitID,
_etblUnits1.cUnitCode as 'parkSize',
_etblUnits2.cUnitCode as 'quantitySize',
InvNum.fInvTotExclForeign,
[_btblInvoiceLines].*,
[_rtblCountry].cCountryName,
[CurrencyHist].fBuyRate,
Vendor.Name,
InvNum.OrderDate,
InvNum.InvNumber
FROM
[dbo].[_btblInvoiceLines]
LEFT JOIN
StkItem ON StkItem.StockLink = [_btblInvoiceLines].iStockCodeID
LEFT JOIN
_etblUnits as _etblUnits1 ON _etblUnits1.idunits = StkItem.iUOMDefSellUnitID
LEFT JOIN
_etblUnits as _etblUnits2 ON _etblUnits2.idunits = StkItem.iUOMStockingUnitID
LEFT JOIN
InvNum ON iInvoiceID = AutoIndex
LEFT JOIN
Vendor ON Vendor.DCLink = InvNum.AccountID
LEFT JOIN
[_rtblCountry] ON [_rtblCountry].idCountry = Vendor.iCountryID
LEFT JOIN
[CurrencyHist] ON InvNum.ForeignCurrencyID = [CurrencyHist].iCurrencyID
WHERE
OrderNum = ''
AND [CurrencyHist].iCurrencyID = (SELECT TOP 1 iCurrencyID
FROM [CurrencyHist]
WHERE iCurrencyID = InvNum.ForeignCurrencyID
ORDER BY idCurrencyHist DESC)
Here is the query, any help will be highly appreciated, thanks in advance
From your previous comments, The problem is coming when you join [CurrencyHist]. From the name, it seems it's a history table and so must be having multiple rows as a history for each currency. To eliminate duplicate rows, you should join with the latest updated record for the particular currency. So, your query could be like below,
SELECT StkItem.iUOMStockingUnitID,
_etblUnits1.cUnitCode as 'parkSize',
_etblUnits2.cUnitCode as 'quantitySize',
InvNum.fInvTotExclForeign,
[_btblInvoiceLines].*,
[_rtblCountry].cCountryName,
[CurrencyHist].fBuyRate,
Vendor.Name,
InvNum.OrderDate,
InvNum.InvNumber
FROM [dbo].[_btblInvoiceLines]
LEFT JOIN StkItem ON StkItem.StockLink = [_btblInvoiceLines].iStockCodeID
LEFT JOIN _etblUnits as _etblUnits1 ON _etblUnits1.idunits = StkItem.iUOMDefSellUnitID
LEFT JOIN _etblUnits as _etblUnits2 ON _etblUnits2.idunits = StkItem.iUOMStockingUnitID
LEFT JOIN InvNum ON iInvoiceID = AutoIndex
LEFT JOIN Vendor ON Vendor.DCLink = InvNum.AccountID
LEFT JOIN [_rtblCountry] ON [_rtblCountry].idCountry = Vendor.iCountryID
LEFT JOIN (SELECT DENSE_RANK() over (partition by [CurrencyHist].iCurrencyID order by [CurrencyHist].LastUpdated desc) as rn,[CurrencyHist].iCurrencyID as 'iCurrencyID'
FROM [CurrencyHist] AS [CurrencyHist]
)[CurrencyHist] ON InvNum.ForeignCurrencyID = [CurrencyHist].iCurrencyID
and [CurrencyHist].rn=1
WHERE OrderNum = '' AND
[CurrencyHist].iCurrencyID = (SELECT TOP 1 iCurrencyID
FROM [CurrencyHist]
WHERE iCurrencyID = InvNum.ForeignCurrencyID
ORDER BY idCurrencyHist DESC)
Note : I have assumed that CurrencyHist table has a LastUpdated with DateTime datatype Column

Limitting results in association

I want to limit the results in a lateral join, so that it only returns the N most recent matches.
This is my query, but the limit inside the join does not seem to work, as it returns all visitors
select am.id, am.title, ame.event, array_agg(row_to_json(visitors))
from auto_messages am
left join apps a on am.app_id = a.id
left join app_users au on a.id = au.app_id
left join auto_message_events ame on ame.auto_message_id = am.id
left join lateral (
select
id,
name,
avatar,
ame.inserted_at
from visitors v
where v.id = ame.visitor_id
order by ame.inserted_at desc
limit 1
) as visitors on visitors.id = ame.visitor_id
where am.id = '100'
group by am.id, ame.event
I am pretty sure the problem is with ame. That is where the rows are generated. The join to visitors is only picking up additional information.
So, this might solve your problem:
select am.id, am.title, visitors.event, array_agg(row_to_json(visitors))
from auto_messages am left join
apps a
on am.app_id = a.id left join
app_users au
on a.id = au.app_id left join lateral
(select v.id, v.name, v.avatar,
ame.event, ame.inserted_at, ame.auto_message_id
from auto_message_events ame join
visitors v
on v.id = ame.visitor_id
order by ame.inserted_at desc
limit 1
) visitors
on visitors.auto_message_id = am.id
where am.id = '100'
group by am.id, visitors.event;
You also might want to change your select clause, if you only want a subset of columns.

Postgresql distinct issue

It needs receiving unique profiles ordered by creation_date. There is following query:
SELECT DISTINCT profiles.id, COALESCE(occured_at, users_visitors.created_at, visitors.created_at) creation_date FROM "profiles"
JOIN "visitors" ON "visitors"."profile_id" = "profiles"."id"
LEFT JOIN events ON profiles.id = events.profile_id
LEFT JOIN event_kinds ON event_kinds.id = events.event_kind_id
LEFT JOIN users_visitors ON visitors.id = users_visitors.visitor_id
WHERE (event_kinds.name = 'enter') AND "users_visitors"."user_id" = 2
ORDER BY creation_date asc
DISTINCT ON (profiles.id) won't help once it should be used for ordering. GROUP BY profiles.id, ... doesn't work as well.
Could you help me, please?
Does this GROUP BY work? Or which creation_date do you want - if not the max one?
SELECT profiles.id,
MAX(COALESCE(occured_at,
users_visitors.created_at,
visitors.created_at)) creation_date
FROM "profiles"
JOIN "visitors" ON "visitors"."profile_id" = "profiles"."id"
LEFT JOIN events ON profiles.id = events.profile_id
LEFT JOIN event_kinds ON event_kinds.id = events.event_kind_id
AND event_kinds.name = 'enter'
LEFT JOIN users_visitors ON visitors.id = users_visitors.visitor_id
AND "users_visitors"."user_id" = 2
GROUP BY profiles.id
ORDER BY creation_date asc
Note how I've moved the where clause conditions to get the LEFT JOIN's to perform as LEFT JOIN's.

Merge 2 SQL query CodeIgniter

I would like to merge these 2 queries to retrieve my datas in a view :
QUERY 1 :
$query = $this->db->query('SELECT ft_upload_data.*, ft_categories.*, ft_categories.category_name
FROM ft_upload_data
LEFT JOIN assigned_categories ON assigned_categories.ft_upload_data_id = ft_upload_data.post_id
LEFT JOIN ft_categories ON ft_categories.cat_id = assigned_categories.ft_categories_id
ORDER BY ft_upload_data.rank ASC
');
return $query->result();
QUERY 2 :
$query2 = $this->db->query('SELECT a.post_id,
COUNT(*) AS num_comments
FROM ft_upload_data a
JOIN ft_comments c ON c.post_id = a.post_id
GROUP BY a.post_id');
return $query2->result();
I can't figure it out :/ Any ideas to trick this?
Thanks !
The simplest (but not necessarily the most efficient) way would be to do it in an in-line query:
SELECT ft_upload_data.*, ft_categories.*,
(SELECT COUNT(*)
FROM ft_comments c
where c.post_id = ft_upload_data.post_id) AS num_comments
FROM ft_upload_data
LEFT JOIN assigned_categories
ON assigned_categories.ft_upload_data_id = ft_upload_data.post_id
LEFT JOIN ft_categories
ON ft_categories.cat_id = assigned_categories.ft_categories_id
ORDER BY ft_upload_data.rank ASC
A more efficient way would be to join to the ft_comments table and group by post_id (assuming that this uniquely identifies ft_upload_data rows), like so:
SELECT ft_upload_data.post_id,
/* include the maximum of each required field from ft_upload_data and
ft_categories here, with appropriate aliases */
COUNT(*) AS num_comments
FROM ft_upload_data
LEFT JOIN assigned_categories
ON assigned_categories.ft_upload_data_id = ft_upload_data.post_id
LEFT JOIN ft_categories
ON ft_categories.cat_id = assigned_categories.ft_categories_id
LEFT JOIN ft_comments c
on c.post_id = ft_upload_data.post_id
GROUP BY ft_upload_data.post_id
ORDER BY max(ft_upload_data.rank) ASC