MySQL - Trouble to run a query - mysql

I have a query that I select some columns and I do left join. I'm using MariaDB at MySQL Workbench.
The Query that I trying to run
sequelize.query(`SELECT
distinct av.idAnnouncementVehicles as id,
av.price,
CONCAT("https://autoparanaiba.s3-sa-east-1.amazonaws.com/" , SUBSTRING_INDEX(ap.image, '.', 1) , '-355x180.' , SUBSTRING_INDEX(ap.image, '.', -1)) as image,
am.worked_hours,
am.year AS ano,
md.description AS modelo,
bn.description AS marca,
fu.description AS combustivel,
pw.description AS potência,
tc.description AS tração
FROM announcement_vehicles AS av
left join announcemment_photos AS ap on ap.annoucements_id = av.idAnnouncementVehicles
left join persons AS pe on pe.id = av.personId
left join agricultural_machine AS am on am.agricultural_machine_id = av.itemId
left join itens AS it on it.id = av.itemId
left join traction AS tc on tc.id = trac.traction_id
left join power AS pw on pw.id = trac.power_id
left join fuel AS fu on fu.id = trac.fuel_id
where it.type=${type} and (av.plans_id IS NOT NULL or pe.type = 'jud')
group by av.idAnnouncementVehicles order by av.plans_id, av.idAnnouncementVehicles desc limit 8`, { type: sequelize.QueryTypes.SELECT })
.then((result) => {
return res.json({ success: true, result: result })
}).catch((err) => {
return res.status(400).json(err)
})
This query is returning this error to me. But I have a similar query in the code that does not throw this error.
The error
{
"name": "SequelizeDatabaseError",
"parent": {
"code": "ER_BAD_FIELD_ERROR",
"errno": 1054,
"sqlState": "42S22",
"sqlMessage": "Unknown column 'md.description' in 'field list'",
The similar query that I have
sequelize.query(`SELECT
distinct av.idAnnouncementVehicles as id,
av.price,
CONCAT("https://autoparanaiba.s3-sa-east-1.amazonaws.com/" , SUBSTRING_INDEX(ap.image, '.', 1) , '-355x180.' , SUBSTRING_INDEX(ap.image, '.', -1)) as image,
ve.mileage,
fi.marca,
fi.name,
fi.ano,
fi.ano_modelo as modelo,
fu.description as combustivel
FROM announcement_vehicles as av
left join announcemment_photos as ap on ap.annoucements_id = av.idAnnouncementVehicles
left join persons as pe on pe.id = av.personId
left join vehicles as ve on ve.item_id = av.itemId
left join itens as it on it.id = av.itemId
left join fipe as fi on fi.id = ve.fipe_id
left join fuel as fu on fu.id = ve.fuel_id
left join color as co on co.id = ve.color_id
where it.type=${type} and (av.plans_id IS NOT NULL or pe.type = 'jud')
group by av.idAnnouncementVehicles order by av.plans_id, av.idAnnouncementVehicles desc limit 8`, { type: sequelize.QueryTypes.SELECT })
.then((result) => {
return res.json({ success: true, result: result })
}).catch((err) => {
return res.status(400).json(err)
})

I resolved the problem with this query
sequelize.query(`SELECT
distinct av.idAnnouncementVehicles as id,
av.price,
CONCAT("https://autoparanaiba.s3-sa-east-1.amazonaws.com/" , SUBSTRING_INDEX(ap.image, '.', 1) , '-355x180.' , SUBSTRING_INDEX(ap.image, '.', -1)) as image,
am.worked_hours,
am.year AS ano,
md.description AS modelo,
bn.description AS marca,
fu.description AS combustivel,
pw.power AS potência,
tc.description AS tração
FROM announcement_vehicles AS av
left join announcemment_photos AS ap on ap.annoucements_id = av.idAnnouncementVehicles
left join persons AS pe on pe.id = av.personId
left join agricultural_machine AS am on am.agricultural_machine_id = av.itemId
left join model_agricultural_machine as md on md.id = am.model_agricultural_machine_id
left join brand_agricultural_machine as bn on bn.id = am.brand_agricultural_machine_id
left join tractor as trc on trc.tractor_id = am.agricultural_machine_id
left join power as pw on pw.id = trc.power_id
left join itens AS it on it.id = av.itemId
left join traction AS tc on tc.id = trc.traction_id
left join fuel AS fu on fu.id = trc.fuel_id
where it.type=${type} and (av.plans_id IS NOT NULL or pe.type = 'jud')
group by av.idAnnouncementVehicles order by av.plans_id, av.idAnnouncementVehicles desc limit 8`, { type: sequelize.QueryTypes.SELECT })
.then((result) => {
return res.json({ success: true, result: result })
}).catch((err) => {
return res.status(400).json(err)
})

Related

mysql creating sort index making queries slow

We have a view table the query for the view is pasted below. The problem is that whenever we try to query items view our database start making sorting index which make the over all time of our response very slow.
CREATE VIEW items_view AS
SELECT item_detail.*, item.name, item.description, item.thumbnail_url, item.large_image_url, item.ios_url, item.android_url, item.vr_url, item.vr_updated_url, item.webgl_url, item.video_url, item.quest_url,
item.is_transferable, item.ip_id, item.brand_id, item.edition_id, item.currency_id, item.category_id, item.rarity_id, item.type_id, item.asset_id, item.artist_id, item.art_collection_id,
IFNULL(item.variation_id, 0) AS variation_id,
item.series_id, item.set_id, item.is_tradable, item.number_minted, ip.name AS ip_name, brand.name As brand_name, brand.value AS brand_image,
edition.name AS edition_name, type.name As type_name, artist.name AS artist_name, art_collection.name AS art_collection_name,
IFNULL(variation.name, '') As variation_name, variation.value AS variation_value, category.name As category_name, asset.name AS asset_name, asset.value AS asset_image,
rarity.name As rarity_name, currency.symbol, currency.code AS currency_code, currency.name AS currency_name, series.name AS series_name, sets.name AS set_name,
CONCAT(users.first_name, ' ' ,users.last_name) as owner_name, users.username AS owner_username, users.is_public_inventory, users.role, users.pub_key,
auctions.id as auction_id, auctions.expire_at as auction_expire_at, max(ab.bid_amount) AS highest_bid_amount, IF(COUNT(auctions.id) > 0 AND !auctions.is_completed AND !auctions.is_deleted
, true, false) AS is_auction, auctions.start_amount AS auction_start_amount, auctions.reserved_amount AS auction_reserved_amount, auctions.buy_now_amount AS auction_buy_now_amount,
auctions.created_at as auction_created_at, auctions.status AS auction_status, auctions.is_extended AS auction_extended, TIMESTAMPDIFF(SECOND, now(), auctions.expire_at) AS auction_expire_seconds FROM item
LEFT JOIN base_lookup AS ip ON item.ip_id = ip.id
LEFT JOIN base_lookup AS brand ON item.brand_id = brand.id
LEFT JOIN base_lookup AS edition ON item.edition_id = edition.id
LEFT JOIN base_lookup AS category ON item.category_id = category.id
LEFT JOIN base_lookup AS type ON item.type_id = type.id
LEFT JOIN base_lookup AS variation ON item.variation_id = variation.id
LEFT JOIN base_lookup AS rarity ON item.rarity_id = rarity.id
LEFT JOIN base_lookup AS series ON item.series_id = series.id
LEFT JOIN base_lookup AS sets ON item.set_id = sets.id
LEFT JOIN base_lookup AS asset ON item.asset_id = asset.id
LEFT JOIN base_lookup AS artist ON item.artist_id = artist.id
LEFT JOIN base_lookup AS art_collection ON item.art_collection_id = art_collection.id
INNER JOIN item_detail ON item.id = item_detail.parent_id
INNER JOIN users ON users.id = item_detail.owner_id
LEFT JOIN currency ON currency.id = item.currency_id
LEFT JOIN auctions on (item_detail.id = auctions.item_detail_id AND auctions.is_deleted = 0 AND auctions.is_completed = 0)
LEFT JOIN auction_bidding ab on auctions.id = ab.auction_id
WHERE item_detail.is_active = 1
group by item_detail.id
order by item_detail.id;
One of the query we are doing on this items_view that is stuck in making sorting index
SELECT
`id`, `code`, `name`, `large_image_url`,
`thumbnail_url`, `medium_thumbnail_url`, `symbol`, `ip_name`, `owner_id`,
`auction_id`, `is_auction`, `highest_bid_amount`, `auction_expire_at`,
`auction_start_amount`, `enable_sale`, `owner_name`, `role`, `amount`,
`auction_expire_seconds`, `rarity_name`, `ip_content`, `asset_content`
FROM `items_view` AS `items_view`
WHERE `items_view`.`transaction_hash` IS NOT NULL AND
`items_view`.`lobby_name` = 'live' AND
`items_view`.`is_tradable` = 1 AND
`items_view`.`is_transferring` = 0 AND
`items_view`.`is_locked` = 0 AND
`items_view`.`enable_sale` = true AND
`items_view`.`is_auction` = 0
ORDER BY `items_view`.`item_order` ASC LIMIT 24, 24;
can any give any suggest what are we doing wrong here!
Edited:
link to explain run against the above query
link to csv

how to full outer join with 3 tables in sql?

I have 3 tables :
table1 : "vw_dimserver" :[ServerKey,ServerNm,ServerCurrentAssignedToNm] for example : [1234,hasgapp0108,Aya]
table2 "vw_DimWorker" : [WorkerEmailNm, WorkerIdsid] . for example : [Aya, akhate] , [Genna,gshysh] , [mish,mishka] (it's like name and username)
table3 "vw_FactHardwareAssetContact" : [ServerKey,HardwareAssetWorkerKey, HardwareAssetContactTypeNm]. for example : [1234,Aya,support]
[1234,Genna,Customer]
[1234,Mish,patch] ( it's server key and the name of the contact and the contact type, if it's support or customer or patch)
I need the output to be in one row:
[ServerNm,WorkerIdsid of the ServerCurrentAssignedToNm, WorkerIdsid of the Customer, WorkerIdsid of the support]
[hasgapp0108,akhate,gshysh,mishka]
Now I need joins with the usernames table to get the username of each user.
I did it with Full outer join.
the code is :
SELECT
vw_dimserver.ServerNm as hostname ,
(vw_DimWorker1.WorkerIdsid) as username,
(vw_DimWorker2.WorkerIdsid) as [Primary Support Contact],
(vw_DimWorker3.WorkerIdsid) as [Primary Customer Contact]
from vw_dimserver
inner join vw_FactHardwareAssetContact on vw_dimserver.ServerKey = vw_FactHardwareAssetContact.HardwareAssetKey
inner join vw_DimWorker as vw_DimWorker1 on vw_DimWorker1.WorkerEmailNm = vw_dimserver.ServerCurrentAssignedToNm
full outer join vw_DimWorker as vw_DimWorker2 on CONVERT(varchar(11),vw_FactHardwareAssetContact.HardwareAssetWorkerKey ) = vw_DimWorker2.workerWWID and vw_FactHardwareAssetContact.HardwareAssetContactTypeNm = 'Support' and vw_FactHardwareAssetContact.HardwareAssetPrimaryInd = '1' and( vw_FactHardwareAssetContact.HardwareAssetWorkerKey is not NULL)
full outer join vw_DimWorker as vw_DimWorker3 on CONVERT(varchar(11),vw_FactHardwareAssetContact.HardwareAssetWorkerKey ) = vw_DimWorker3.workerWWID and vw_FactHardwareAssetContact.HardwareAssetContactTypeNm = 'Customer' and vw_FactHardwareAssetContact.HardwareAssetPrimaryInd = '1' and( vw_FactHardwareAssetContact.HardwareAssetWorkerKey is not NULL)
where vw_dimserver.ServerNm ='hasgapp0108' and (vw_DimWorker2.workerWWID is not null or vw_DimWorker3.workerWWID is not null ) and ( ServerCurrentSubStatusCd != 'duplicate_error' or ServerCurrentSubStatusCd is NULL )
The output is two rows:
[hostname username Support Customer ]
[hasgapp0108 akhate NULL gshysh],
[hasgapp0108 akhate akhate NULL]
and I need it to be one row :
[hostname username Support Customer]
[hasgapp0108 akhate akhate gshysh]
My manager didn't accept the solutaion :
select max(username1),max(username2)...
I need to do it with joins.
Try this with inner join and group_concat:
SELECT vw_dimserver.ServerNm as hostname , group_concat(vw_DimWorker1.WorkerIdsid) as username, group_concat(vw_DimWorker2.WorkerIdsid) as [Primary Support Contact], group_concat(vw_DimWorker3.WorkerIdsid) as [Primary Customer Contact]
from vw_dimserver
inner join vw_FactHardwareAssetContact on vw_dimserver.ServerKey = vw_FactHardwareAssetContact.HardwareAssetKey
inner join vw_DimWorker as vw_DimWorker1 on vw_DimWorker1.WorkerEmailNm = vw_dimserver.ServerCurrentAssignedToNm
full outer join vw_DimWorker as vw_DimWorker2 on CONVERT(varchar(11),vw_FactHardwareAssetContact.HardwareAssetWorkerKey ) = vw_DimWorker2.workerWWID and vw_FactHardwareAssetContact.HardwareAssetContactTypeNm = 'Support' and vw_FactHardwareAssetContact.HardwareAssetPrimaryInd = '1' and( vw_FactHardwareAssetContact.HardwareAssetWorkerKey is not NULL)
full outer join vw_DimWorker as vw_DimWorker3 on CONVERT(varchar(11),vw_FactHardwareAssetContact.HardwareAssetWorkerKey ) = vw_DimWorker3.workerWWID and vw_FactHardwareAssetContact.HardwareAssetContactTypeNm = 'Customer' and vw_FactHardwareAssetContact.HardwareAssetPrimaryInd = '1' and( vw_FactHardwareAssetContact.HardwareAssetWorkerKey is not NULL)
where vw_dimserver.ServerNm ='hasgapp0108' and (vw_DimWorker2.workerWWID is not null or vw_DimWorker3.worker
group by vw_dimserver.ServerNm
You could use an inner join if you need only matching result
SELECT
s.ServerKey,
s.ServerNm,
group_concat(w.WorkerIdsid)
FROM vw_dimserver s
INNER JOIN vw_FactHardwareAssetContact c
ON s.ServerKey = c.ServerKey
INNER JOIN vw_DimWorker w
ON c.HardwareAssetWorkerKey = w.WorkerEmailNm
GROUP BY s.ServerKey,
s.ServerNm
OR You could use left join if there are not all matching
SELECT
s.ServerKey,
s.ServerNm,
group_concat(w.WorkerIdsid)
FROM vw_dimserver s
LEFT JOIN vw_FactHardwareAssetContact c
ON s.ServerKey = c.ServerKey
LEFT JOIN vw_DimWorker w
ON c.HardwareAssetWorkerKey = w.WorkerEmailNm
GROUP BY s.ServerKey,
s.ServerNm
SELECT vw_dimserver.ServerNm as hostname , (vw_DimWorker1.WorkerIdsid) as username, (vw_DimWorker2.WorkerIdsid) as [Primary Support Contact], (vw_DimWorker3.WorkerIdsid) as [Primary Customer Contact]
from vw_dimserver
full outer join vw_FactHardwareAssetContact as vw_FactHardwareAssetContact1
on (vw_dimserver.ServerKey = vw_FactHardwareAssetContact1.HardwareAssetKey and vw_FactHardwareAssetContact1.HardwareAssetContactTypeNm = 'Support' and vw_FactHardwareAssetContact1.HardwareAssetPrimaryInd = '1' )
full outer join vw_DimWorker as vw_DimWorker1 on CONVERT(varchar(11),vw_FactHardwareAssetContact1.HardwareAssetWorkerKey ) = vw_DimWorker1.workerWWID
full outer join vw_DimWorker as assings on assings.WorkerEmailNm = vw_dimserver.ServerCurrentAssignedToNm
full outer join vw_FactHardwareAssetContact as vw_FactHardwareAssetContact2 on (vw_dimserver.ServerKey = vw_FactHardwareAssetContact2.HardwareAssetKey and vw_FactHardwareAssetContact2.HardwareAssetContactTypeNm = 'Customer' and vw_FactHardwareAssetContact2.HardwareAssetPrimaryInd = '1' )
full outer join vw_DimWorker as vw_DimWorker2 on CONVERT(varchar(11),vw_FactHardwareAssetContact2.HardwareAssetWorkerKey ) = vw_DimWorker2.workerWWID
full OUTER join vw_FactHardwareAssetContact as vw_FactHardwareAssetContact11 on (vw_dimserver.ServerKey = vw_FactHardwareAssetContact11.HardwareAssetKey and vw_FactHardwareAssetContact11.HardwareAssetContactTypeNm = 'Support' and vw_FactHardwareAssetContact11.HardwareAssetPrimaryInd = '0' )
full outer join vw_DimWorker as vw_DimWorker11 on CONVERT(varchar(11),vw_FactHardwareAssetContact11.HardwareAssetWorkerKey ) = vw_DimWorker11.workerWWID
full OUTER join vw_FactHardwareAssetContact as vw_FactHardwareAssetContact22 on (vw_dimserver.ServerKey = vw_FactHardwareAssetContact22.HardwareAssetKey and vw_FactHardwareAssetContact22.HardwareAssetContactTypeNm = 'Customer' and vw_FactHardwareAssetContact11.HardwareAssetPrimaryInd = '0' )
full outer join vw_DimWorker as vw_DimWorker22 on CONVERT(varchar(11),vw_FactHardwareAssetContact22.HardwareAssetWorkerKey ) = vw_DimWorker22.workerWWID

Return data from VIEWS using Knex.js

How can I get data from views in my mysql database using knex.js ?
I want to return this data in my nodejs route.get
SELECT c.id, nome_1
FROM pessoas_juridicas as pj
INNER JOIN pessoas as p
ON p.id = pj.pessoa_id
INNER JOIN clientes as c
ON c.pessoa_id = pj.pessoa_id
UNION
SELECT c.id, nome_1
FROM pessoas_fisicas as pf
INNER JOIN pessoas as p
ON p.id = pf.pessoa_id
INNER JOIN clientes as c
ON c.pessoa_id = pf.pessoa_id
WHERE p.id = 1
;
let sql = knex.from('live_calls' + ' as r')
.select('r.uuid', 'r.destination', 'r.current_status', 'r.src')
.where('r.uuid', '=', uuid );
sql.then((response) => {
console.log(response);
});
Here live_calls is a MySQL View.

yii2 query takes too much time to load data

$query = IroningOrder::find()->alias("io")->select(["io.*", "u1.username as createdByUser", "u2.username as updatedByUser", "concat(c.first_name, ' ', c.last_name) AS customer_name", "CONCAT(ud1.first_name , ' ', ud1.last_name) as pickedUpBy", "CONCAT(ud2.first_name , ' ', ud2.last_name) as deliveredBy", "ioe3.updated_at as delivered_at"])
->join("LEFT JOIN", "user u1", "u1.id = io.created_by")
->join("LEFT JOIN", "user u2", "u2.id = io.updated_by")
->join("INNER JOIN", "tbl_customer c", "c.id = io.customer_id")
->join("LEFT JOIN", "tbl_ironing_order_emp_allocation ioe1", "ioe1.ironing_order_id = io.id")
->join("LEFT JOIN", "tbl_ironing_order_emp_allocation ioe2", "ioe2.ironing_order_id = io.id")
->join("LEFT JOIN", "tbl_ironing_order_emp_allocation ioe3", "ioe3.ironing_order_id = io.id AND ioe3.type = 'DELIVERY' AND io.delivery_status = 'COMPLETE'")
->join("LEFT JOIN", "tbl_user_details ud1", "ud1.user_id = ioe1.user_id AND ioe1.type = 'PICKUP'")
->join("LEFT JOIN", "tbl_user_details ud2", "ud2.user_id = ioe2.user_id AND ioe2.type = 'DELIVERY'")
->join("LEFT JOIN", "tbl_delivery_address da", "da.id = io.delivery_address_id")
->groupBy(["io.id"]);
SELECT `io`.`id`, `io`.`customer_id`, `io`.`status`, `io`.`pickup_status`, `io`.`allocated_bag_id`, `io`.`inward_status`, `io`.`outward_status`, `io`.`ironman_status`, `io`.`created_at`, `io`.`updated_at`, `io`.`delivery_status`, `u1`.`username` AS `createdByUser`, `io`.`total`, `u2`.`username` AS `updatedByUser`, concat(c.first_name, ' ', c.last_name) AS customer_name, CONCAT(ud1.first_name , ' ', ud1.last_name) as pickedUpBy, CONCAT(ud2.first_name , ' ', ud2.last_name) as deliveredBy, `ioe3`.`updated_at` AS `delivered_at`
FROM `tbl_ironing_order` `io`
LEFT JOIN `user` `u1` ON u1.id = io.created_by
LEFT JOIN `user` `u2` ON u2.id = io.updated_by
INNER JOIN `tbl_customer` `c` ON c.id = io.customer_id
LEFT JOIN `tbl_ironing_order_emp_allocation` `ioe1` ON ioe1.ironing_order_id = io.id
LEFT JOIN `tbl_ironing_order_emp_allocation` `ioe2` ON ioe2.ironing_order_id = io.id
LEFT JOIN `tbl_ironing_order_emp_allocation` `ioe3` ON ioe3.ironing_order_id = io.id AND ioe3.type = 'DELIVERY' AND io.delivery_status = 'COMPLETE' LEFT JOIN `tbl_user_details` `ud1` ON ud1.user_id = ioe1.user_id AND ioe1.type = 'PICKUP'
LEFT JOIN `tbl_user_details` `ud2` ON ud2.user_id = ioe2.user_id AND ioe2.type = 'DELIVERY'
LEFT JOIN `tbl_delivery_address` `da` ON da.id = io.delivery_address_id GROUP BY `io`.`id`
When i run this query it will give me proper result set,But it will take too much time to load page.Please help me to optimize above query

mysql using outside alias to 2 level deep subquery

I'm currently stuck here and don't know what to do next since I can't use the tv_main alias into the 2 level deep subquery. Here's my code (I commented the part that have a problem). Any help will be appreciated. Thanks.
SELECT tv_main.id,
tv_main.vesselName,
(
SELECT SUM(t_statCtr.status = 'EX CREW')
FROM
(
(
SELECT tpi_stat.id,
tvv.vesselName,
lastname,
firstname,
middlename,
IF(tpi_stat.returningCrew = 1, 'NEW HIRE',
IF(COUNT(tc_ctr.personnel_id) > 1, 'EX CREW', 'NEW HIRE')
)
AS status
FROM tbl_contracts AS tc_stat
LEFT JOIN tbl_personnel_info AS tpi_stat
ON tpi_stat.id = tc_stat.personnel_id
LEFT JOIN tbl_contracts AS tc_ctr
ON tpi_stat.id = tc_ctr.personnel_id
LEFT JOIN tbl_vessels AS tvv
ON tvv.id = tpi_stat.lastJoinedVsl
WHERE
tpi_stat.emp_status = 'ON-BOARD'
AND tc_stat.status = 'ACTIVE'
AND tvv.id = tv_main.id --This line have an error, (Unknown Column tv_main.id in where clause)
GROUP BY tc_stat.personnel_id
) AS t_statCtr
)
) AS ex_crew,
NULL AS new_hire
FROM tbl_vessels AS tv_main -- I need this one to use inside the subquery
LEFT JOIN tbl_personnel_info AS tpi
ON tv_main.id = tpi.lastJoinedVsl
LEFT JOIN tbl_contracts AS tc
ON tpi.id = tc.personnel_id
WHERE
tpi_stat.emp_status = 'ON-BOARD'
AND tc_stat.status = 'ACTIVE'
GROUP BY tv_main.vesselName
I finally solve it. I didn't know that mysql only allow correlation of 1 deep level.
SELECT tv_main.vesselName,
SUM(t_dummy.statusx = 'EX CREW') AS ex_crew,
SUM(t_dummy.statusx = 'NEW HIRE') AS new_hire
FROM tbl_vessels AS tv_main
LEFT JOIN tbl_personnel_info AS tpi_main
ON tpi_main.lastJoinedVsl = tv_main.id
LEFT JOIN tbl_contracts AS tc_main
ON tc_main.personnel_id = tpi_main.id
LEFT JOIN
(
SELECT tvv.id,
tpi_stat.id AS tpiid,
IF(tpi_stat.returningCrew = 1, 'NEW HIRE',
IF(COUNT(tc_ctr.personnel_id) > 1, 'EX CREW', 'NEW HIRE')
)
AS statusx
FROM tbl_contracts AS tc_stat
LEFT JOIN tbl_personnel_info AS tpi_stat
ON tpi_stat.id = tc_stat.personnel_id
LEFT JOIN tbl_contracts AS tc_ctr
ON tpi_stat.id = tc_ctr.personnel_id
LEFT JOIN tbl_vessels AS tvv
ON tvv.id = tpi_stat.lastJoinedVsl
GROUP BY tc_stat.personnel_id
) AS t_dummy
ON tpi_main.id = t_dummy.tpiid
WHERE
tpi_main.emp_status = 'ON-BOARD'
AND tc_main.status = 'ACTIVE'
AND t_dummy.id = tv_main.id
GROUP BY tv_main.vesselName;