mysql using outside alias to 2 level deep subquery - mysql

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;

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 limit record in left join

SELECT commerce_product_field_data_commerce_product__field_data_field_products.entity_id, field_products_commerce_product.nid FROM commerce_order o
join commerce_payment_transaction t on o.order_id = t.order_id
join commerce_line_item i on o.order_id = i.order_id
LEFT JOIN field_data_commerce_total s ON i.line_item_id = s.entity_id AND (s.entity_type = 'commerce_line_item' AND s.deleted = '0')
LEFT JOIN field_data_commerce_product field_data_commerce_product ON i.line_item_id = field_data_commerce_product.entity_id AND (field_data_commerce_product.entity_type = 'commerce_line_item' AND field_data_commerce_product.deleted = '0')
INNER JOIN commerce_product commerce_product_field_data_commerce_product ON field_data_commerce_product.commerce_product_product_id = commerce_product_field_data_commerce_product.product_id
LEFT JOIN
(select * from field_data_field_products)
commerce_product_field_data_commerce_product__field_data_field_products ON commerce_product_field_data_commerce_product.product_id = commerce_product_field_data_commerce_product__field_data_field_products.field_products_product_id
LEFT JOIN ( select nid as nid from node order by nid)
field_products_commerce_product
ON commerce_product_field_data_commerce_product__field_data_field_products.entity_id = field_products_commerce_product.nid LEFT JOIN (
select r.entity_id, r.field_ranges_value from field_data_field_ranges r
) r
on r.entity_id = field_products_commerce_product.nid
WHERE t.status = 'success' and i.type = 'product' and o.Uid <> 0
AND o.status IN ('completed') and o.created >= '1483228800' and o.created <= '1483315200' and r.field_ranges_value = 'Tasty Sticks'
Is my sql
It is giving me 5 results. I only need 4
One of the product id's belong to two Drupal nodes and I only want one of them
I tried changing LEFT JOIN ( select nid as nid from node order by nid) to
LEFT JOIN ( select nid as nid from node order by nid limit 1) but then I don't get any records at all. Any idea what needs changing please other than removing one of the duplicate nodes. Thanks

SQL orderby select

i have SQL query. I would like to orderby this by parent category. But i return only default category. I would like to know if i can
ORDER BY SELECT id_parent FROM cats WHERE id_category = id_default_category
Here is my query :
SELECT cp.`id_product_attribute`,
cp.`id_product`, cp.`quantity` AS cart_quantity,
cp.id_shop, pl.`name`,
p.`is_virtual`,
pl.`description_short`,
pl.`available_now`,
pl.`available_later`,
product_shop.`id_category_default`,
p.`id_supplier`,
p.`id_manufacturer`,
product_shop.`on_sale`,
product_shop.`ecotax`,
product_shop.`additional_shipping_cost`,
product_shop.`available_for_order`,
product_shop.`price`,
product_shop.`active`,
product_shop.`unity`,
product_shop.`unit_price_ratio`,
stock.`quantity` AS quantity_available,
p.`width`,
p.`height`,
p.`depth`,
stock.`out_of_stock`,
p.`weight`,
p.`date_add`,
p.`date_upd`,
IFNULL(stock.quantity, 0) as quantity,
pl.`link_rewrite`,
cl.`link_rewrite` AS category,
CONCAT(LPAD(cp.`id_product`, 10, 0),
LPAD(IFNULL(cp.`id_product_attribute`, 0), 10, 0),
IFNULL(cp.`id_address_delivery`, 0)) AS unique_id,
cp.id_address_delivery,
product_shop.advanced_stock_management,
ps.product_supplier_reference supplier_reference
FROM `ps_cart_product` cp
LEFT JOIN `ps_product` `p` ON p.`id_product` = cp.`id_product`
INNER JOIN `ps_product_shop` product_shop ON (product_shop.`id_shop` = cp.`id_shop` AND product_shop.`id_product` = p.`id_product`)
LEFT JOIN `ps_product_lang` `pl` ON p.`id_product` = pl.`id_product`
AND pl.`id_lang` = 1 AND pl.id_shop = cp.id_shop
LEFT JOIN `ps_category_lang` `cl` ON product_shop.`id_category_default` = cl.`id_category`
AND cl.`id_lang` = 1 AND cl.id_shop = cp.id_shop
LEFT JOIN `ps_product_supplier` `ps` ON ps.`id_product` = cp.`id_product` AND ps.`id_product_attribute` = cp.`id_product_attribute` AND ps.`id_supplier` = p.`id_supplier`
LEFT JOIN ps_sanishopstock_available stock
ON (stock.id_product = cp.id_product AND stock.id_product_attribute = IFNULL(`cp`.id_product_attribute, 0) AND stock.id_shop = 1 AND stock.id_shop_group = 0 )
WHERE cp.`id_cart` = 757
ORDER BY product_shop.id_category_default ASC, cp.id_product, cp.date_add ASC;
There is a lot of different table, i'm lost !
If someone have any idea.
Thanks a lot !
Yes. But like any subquery, you need parentheses:
ORDER BY (SELECT c.id_parent FROM cats c WHERE id_category = id_default_category)
I would also qualify the column names in the WHERE, but I don't know where they come from.

MYSQL UNION JOIN SUM(amount) output two result instead of one

I have this below:
SELECT a.* FROM ( SELECT
asset_liability_income_expenditure_tbl.a_l_code,
SUM(mainaccount_a_2017.amount), mainaccount_a_2017.dr_cr_action
FROM `mainaccount_a_2017` LEFT JOIN chart_of_account
ON (
chart_of_account.joint_account_numbers =
mainaccount_a_2017.joint_account_number
)
LEFT JOIN asset_liability_income_expenditure_tbl
ON (
asset_liability_income_expenditure_tbl.a_l_code =
chart_of_account.account_type
)
WHERE asset_liability_income_expenditure_tbl.a_l_code = 'FA'
AND mainaccount_a_2017.dr_cr_action = 'DR' UNION
SELECT asset_liability_income_expenditure_tbl.a_l_code,
SUM(mainaccount_b_2017.amount),
mainaccount_b_2017.dr_cr_action
FROM `mainaccount_b_2017`
LEFT JOIN chart_of_account ON (
chart_of_account.joint_account_numbers =
mainaccount_b_2017.joint_account_number
)
LEFT JOIN asset_liability_income_expenditure_tbl ON (
asset_liability_income_expenditure_tbl.a_l_code =
chart_of_account.account_type
)
WHERE asset_liability_income_expenditure_tbl.a_l_code = 'FA'
AND mainaccount_b_2017.dr_cr_action = 'DR'
) AS a
it works fine, but displays either one empty row at the top and the sum below or vis-a-vis. I tried LIMIT 1, but the problem is when the SUM(amount) outputs in row 2, i cannot fetch and if I don't apply any limit, it only fetches result whose SUM(amount) outputs in row 1. I don't know what am missing. Please kindly assist. Thanks.
I figured it out. I had to flip something. Results below:
SELECT SUM(a) FROM
(
SELECT SUM(mainaccount_a_2017.amount)
AS a FROM `mainaccount_a_2017`
LEFT JOIN chart_of_account ON (chart_of_account.joint_account_numbers = mainaccount_a_2017.joint_account_number)
LEFT JOIN asset_liability_income_expenditure_tbl ON (asset_liability_income_expenditure_tbl.a_l_code = chart_of_account.account_type)
WHERE asset_liability_income_expenditure_tbl.a_l_code = 'FA'
AND mainaccount_a_2017.dr_cr_action = 'DR'
UNION ALL
SELECT SUM(mainaccount_b_2017.amount)
AS a FROM `mainaccount_b_2017`
LEFT JOIN chart_of_account ON (chart_of_account.joint_account_numbers = mainaccount_b_2017.joint_account_number)
LEFT JOIN asset_liability_income_expenditure_tbl ON (asset_liability_income_expenditure_tbl.a_l_code = chart_of_account.account_type)
WHERE asset_liability_income_expenditure_tbl.a_l_code = 'FA' AND mainaccount_b_2017.dr_cr_action = 'DR'
) a

Why MYSQL doesn't use my indexes?

I have table karton00 which holds thousands of records. This makes the queries slow. I would like to use indexes, but even though I set them, they are not being used.
Here is my table. and here is the result of using EXPLAIN.
This is my query:
SELECT '' checkbox,
k00_eszkozid,
k00_eszkoznev,
k01_gyariszam,
k01_leltszam,
prsn_name,
k00_status,
tstikon,
k00_startflow,
tstname,
k00_eszkozid,
k01_gyariszam,
k01_leltszam
FROM karton00
LEFT JOIN karton01
ON k00_eszkozid = k01_eszkozid
AND k01_status = 'A'
LEFT JOIN karton02
ON k00_eszkozid = k02_eszkozid
AND k02_status = 'A'
LEFT JOIN karton04
ON k00_eszkozid = k04_eszkozid
AND k04_status = 'A'
LEFT JOIN karton05
ON k00_eszkozid = k05_eszkozid
AND k05_status = 'A'
LEFT JOIN karton06
ON k00_eszkozid = k06_eszkozid
AND k06_status = 'A'
LEFT JOIN karton08
ON k00_eszkozid = k08_eszkozid
AND k08_status = 'A'
LEFT JOIN karton09
ON k00_eszkozid = k09_eszkozid
AND k09_status = 'A'
LEFT JOIN telephely et
ON k06_telephelyid = et.telepid
LEFT JOIN ktghely00 ek
ON k02_ktghid = ek.ktghid
LEFT JOIN person00 us
ON k06_userid = prsn_id
LEFT JOIN ktghely00 fk
ON prsn_ktgh = fk.ktghid
LEFT JOIN telephely ft
ON prsn_telep = ft.telepid
LEFT JOIN tamstatus
ON k02_tamstatusid = tstid
LEFT JOIN szakleltar
ON k02_szakleltarid = szleltid
LEFT JOIN tamszerv
ON k02_tamszervid = tszid
LEFT JOIN ktghely01
ON k02_vgazdaid = vgid
AND vgstatus = 'A'
LEFT JOIN ktghely00 vk
ON vgktghid = vk.ktghid
LEFT JOIN szallitok m
ON k05_mincegid = m.szallid
LEFT JOIN szallitok s
ON k04_szallitoid = s.szallid
LEFT JOIN dctnry00 ym
ON k05_minosit = ym.dctnryname
AND ym.dctnrygrp = 'YESNO'
LEFT JOIN dctnry00 yd
ON k05_check = yd.dctnryname
AND yd.dctnrygrp = 'YESNO'
WHERE k00_status IN ( 'A', 'H' )
AND ( k02_vgazdaid IN ( 7 ) )
AND NOT EXISTS (SELECT *
FROM eszkozkizar
WHERE ez_flid = 0
AND ez_emintaid = k00_eszkozmintaid
AND k00_uzembedatum < ( Date_add(Curdate(),
INTERVAL ez_honap month) )
AND k00_uzembedatum != ''
AND k02_vgazdaid NOT IN ( 7 ))
AND NOT EXISTS(SELECT *
FROM eszkozkizar
WHERE ez_flid = 0
AND ez_emintaid = k00_eszkozmintaid
AND k02_tamszervid = ez_tamszerv
AND k02_tamstatusid = ez_tamsts
AND k00_uzembedatum < ( Date_add(Curdate(),
INTERVAL ez_honap month) )
AND k00_uzembedatum != ''
AND k02_vgazdaid NOT IN ( 7 ))
ORDER BY k00_eszkoznev ASC;
Also you can use USE INDEX (index_list) statement: http://dev.mysql.com/doc/refman/5.5/en/index-hints.html