MySQL Getting row numbers of table inside subquery - mysql

I have one query where I need to have number of rows of an table by particular ID:
SELECT
(CAST(`ot`.`value` AS DECIMAL(6,2))) AS `value`,
`op`.`orders_id`,
(
SELECT
COUNT(1) AS `total`
FROM
(
SELECT
`op2`.`concert_date`
FROM
`orders_products` `op2`
WHERE
`op2`.`orders_id` = `op`.`orders_id`
AND
`op2`.`concert_date` <> ''
GROUP BY CONCAT(`op2`.`concert_date`,' ',`op2`.`concert_time`)
) AS `e`
) AS `devider`
FROM
`categories` `c`
JOIN `products` `p` ON `p`.`section_id` = `c`.`section_id`
JOIN `orders_products` `op` ON `op`.`products_id` = `p`.`products_id`
JOIN `orders_total` `ot` ON `ot`.`orders_id` = `op`.`orders_id`
WHERE
`c`.`section_id` = 25
AND
`p`.`product_type` IN ('P')
AND
`ot`.`class` IN ('ot_shipping')
GROUP BY `op`.`orders_id`
The main problem is that I getting error
#1054 - Unknown column 'op.orders_id' in 'where clause'
And can't run this. I have separated query in my loop but that made performance issue and want to push it in one query. Any idea?

try removing sub-sub query and use COUNT(DISTINCT ..)
SELECT
(CAST(`ot`.`value` AS DECIMAL(6,2))) AS `value`,
`op`.`orders_id`,
(
SELECT
COUNT(DISTINCT CONCAT(`op2`.`concert_date`,' ',`op2`.`concert_time`))
FROM
`orders_products` `op2`
WHERE
`op2`.`orders_id` = `op`.`orders_id`
AND
`op2`.`concert_date` <> ''
) AS `devider`
FROM
`categories` `c`
JOIN `products` `p` ON `p`.`section_id` = `c`.`section_id`
JOIN `orders_products` `op` ON `op`.`products_id` = `p`.`products_id`
JOIN `orders_total` `ot` ON `ot`.`orders_id` = `op`.`orders_id`
WHERE
`c`.`section_id` = 25
AND
`p`.`product_type` IN ('P')
AND
`ot`.`class` IN ('ot_shipping')
GROUP BY `op`.`orders_id`
and you don't even need subquery or concat as long concert_date or concert_time is null
SELECT
(CAST(`ot`.`value` AS DECIMAL(6,2))) AS `value`,
`op`.`orders_id`,
COUNT(DISTINCT `op`.`concert_date`, `op`.`concert_time`) AS `devider`
FROM
`categories` `c`
JOIN `products` `p` ON `p`.`section_id` = `c`.`section_id`
LEFT JOIN `orders_products` `op` ON `op`.`products_id` = `p`.`products_id`
JOIN `orders_total` `ot` ON `ot`.`orders_id` = `op`.`orders_id`
WHERE
`c`.`section_id` = 25
AND
`p`.`product_type` IN ('P')
AND
`ot`.`class` IN ('ot_shipping')
GROUP BY `op`.`orders_id`

In this subquery:
SELECT
`op2`.`concert_date`
FROM
`orders_products` `op2`
WHERE
`op2`.`orders_id` = `op`.`orders_id`
AND
`op2`.`concert_date` <> ''
GROUP BY CONCAT(`op2`.`concert_date`,' ',`op2`.`concert_time`)
you are not selecting op as table.
Should be:
SELECT
`op2`.`concert_date`
FROM
`orders_products` `op2`, `orders_products` `op`
WHERE
`op2`.`orders_id` = `op`.`orders_id`
AND
`op2`.`concert_date` <> ''
GROUP BY CONCAT(`op2`.`concert_date`,' ',`op2`.`concert_time`)
Beside this you are making an implicit join while you should use explicit even here and the subquery should become:
SELECT
`op2`.`concert_date`
FROM
`orders_products` `op2` JOIN `orders_products` `op`
ON
`op2`.`orders_id` = `op`.`orders_id`
WHERE
`op2`.`concert_date` <> ''
GROUP BY CONCAT(`op2`.`concert_date`,' ',`op2`.`concert_time`)

Related

Unknown column in 'IN/ALL/ANY subquery'

Why am I getting this error? Error is showing up in the OR clause, but I'm selecting gl_ID inside the SELECT statement.
; DECLARE v_firstDate DATETIME
SET #p_ID = 368
SELECT SUBDATE(NOW(), 1) INTO v_firstDate;
SELECT t_ID, t_firstName, t_lastName
FROM t_table
WHERE
((#p_ID IN (
SELECT tt_ID
FROM tt_tableTwo
INNER JOIN st_stats ON (st_ID = tt_ID)
INNER JOIN da_data ON (da_ID = st_ID AND da_name IN ("allCompanies", "allglobals"))
)
))
OR
(
(gl_ID IN ( //problem is here
SELECT gl_ID
FROM gl_globals
INNER JOIN tr_transport ON (tr_id = gl_caseID AND tr_idOther = #p_ID)
INNER JOIN co_countries ON (co_ID = gl_ID AND co_ID = #p_ID)
)
)
)
Error message:
Unknown column 'gl_ID' in 'IN/ALL/ANY subquery'
Should I be using an AS or a HAVING?
gl_ID is not accessible in the OR clause because it doesn't exist in t_table. An inner join under the first FROM clause solves the problem.
; DECLARE v_firstDate DATETIME
SET #p_ID = 368
SELECT SUBDATE(NOW(), 1) INTO v_firstDate;
SELECT t_ID, t_firstName, t_lastName
FROM t_table
INNER JOIN gl_globals ON (t_ID = gl_ID) // fix
WHERE
((#p_ID IN (
SELECT tt_ID
FROM tt_tableTwo
INNER JOIN st_stats ON (st_ID = tt_ID)
INNER JOIN da_data ON (da_ID = st_ID AND da_name IN ("allCompanies", "allglobals"))
)
))
OR
(
(gl_ID IN (
SELECT gl_ID
FROM gl_globals
INNER JOIN tr_transport ON (tr_id = gl_caseID AND tr_idOther = #p_ID)
INNER JOIN co_countries ON (co_ID = gl_ID AND co_ID = #p_ID)
)
)
)

How use custom alias field from select fields in join?

How use custom alias field from select fields in join?
SELECT LOWER(CONCAT(`ufn`.`value`, '.', `uln`.`value`, CAST(RAND()*1e6 AS UNSIGNED))) AS `newlogin`
FROM `user_firstname` AS `ufn`
INNER JOIN `user_lastname` AS `uln`
LEFT JOIN `user` AS `u` ON `u`.`login` = `newlogin`
WHERE `ufn`.`sex` = 'male' AND `u`.`id` IS NULL
ORDER BY RAND()
LIMIT 1
Result: sql-error.png
EDIT:
My solution, but, ...:
SELECT #newlogin
FROM (
SELECT #newlogin := LOWER(CONCAT(`ufn`.`value`, '.', `uln`.`value`, CAST(RAND()*1e6 AS UNSIGNED)))
FROM `user_firstname` AS `ufn`
INNER JOIN `user_lastname` AS `uln`
WHERE `ufn`.`sex` = 'male'
ORDER BY RAND()
LIMIT 1
) AS `ufnX`
LEFT JOIN `user` AS `u` ON `u`.`login` = #newlogin
WHERE `u`.`id` IS NULL
Create the new login in a subquery and join it in:
SELECT LOWER(CONCAT(`ufn`.`value`, '.', `uln`.`value`, nl.num)) AS newlogin
FROM (SELECT CAST(RAND()*1e6 AS UNSIGNED))) AS num
) nl CROSS JOIN
`user_firstname` ufn CROSS JOIN
`user_lastname` uln LEFT JOIN
`user` u
ON `u`.`login` = LOWER(CONCAT(ufn.`value`, '.', uln.`value`, nl.num))
WHERE `ufn`.`sex` = 'male' AND `u`.`id` IS NULL
ORDER BY RAND()
LIMIT 1;
Note I replaced the INNER JOIN with CROSS JOIN. INNER JOIN with no ON makes no sense.
EDIT:
You seem to want to test multiple values to get a match. You could try putting the comparison in the HAVING clause. That clause can reference columns in the SELECT:
SELECT LOWER(CONCAT(ufn.`value`, '.', uln.`value`, CAST(RAND()*1e6 AS UNSIGNED))) AS newlogin
FROM user_firstname` ufn CROSS JOIN
`user_lastname` uln
WHERE `ufn`.`sex` = 'male'
HAVING NOT EXISTS (SELECT 1
FROM user u
WHERE u.login = newlogin
)
ORDER BY RAND()
LIMIT 1;

view select cannot contain from clause

I have a SQL Query. When I run it executes successfully, but when i was trying to create a view with the query it shows create a view with each subquery.
SOS.
SELECT `product_category_vendor_id`,
ct1.category_id,
ct1.category_name,
c1.`product_id`,
p1.product_name,
c1.`vendor_id`,
v1.vendor_name,
c1.`product_purchase_price`,
c1.product_vendor_qty,
d1.available
FROM (SELECT `product_category_vendor_id`,
a1.`product_id`,
a1.`vendor_id`,
a1.`product_purchase_price`,
b2.product_vendor_qty
FROM (SELECT `product_category_vendor_id`,
`product_id`,
`vendor_id`,
`product_purchase_price`
FROM tbl_inksand_product_category_vendor
WHERE product_category_vendor_id IN
(SELECT
Max(product_category_vendor_id) AS
`Product_Category_Vendor_Id`
FROM
tbl_inksand_product_category_vendor
WHERE (
product_category_vendor_status =
'A' )
GROUP BY product_id,
`vendor_id`
ORDER BY `product_id`))
AS a1
JOIN (SELECT `product_id`,
`vendor_id`,
Sum(`product_vendor_qty`) AS Product_Vendor_Qty
FROM tbl_inksand_product_category_vendor
GROUP BY product_id,
`vendor_id`
ORDER BY `product_id`) b2
ON a1.`product_id` = b2.`product_id`
AND a1.`vendor_id` = b2.`vendor_id`) c1
JOIN (SELECT `product_id`,
`vendor_id`,
Count(`item_id`) AS Available
FROM `tbl_inksand_item_dtls`
WHERE `product_item_status` = 'Not Sale'
GROUP BY `product_id`,
`vendor_id`) d1
ON c1.`product_id` = d1.`product_id`
AND c1.`vendor_id` = d1.`vendor_id`
JOIN tbl_inksand_vendor AS v1
ON c1.`vendor_id` = v1.`vendor_id`
JOIN tbl_inksand_product p1
ON p1.product_id = c1.`product_id`
JOIN tbl_inksand_category ct1
ON ct1.category_id = p1.category_id
Subqueries cannot be used in the FROM clause of a view.
Source: https://dev.mysql.com/doc/refman/5.0/en/view-restrictions.html
So yeah it was the right reccomendation to create seperate views.

MYSQL Update AND SUM

i am try to do somethink like this
UPDATE BA C
INNER JOIN
(
SELECT SUM(`Amount`) AS `LSC`,`To` FROM `Trans`
) A ON C.`UserID` = A.`To`
INNER JOIN
(
SELECT SUM(`Amount`) AS `LSC`,`From` FROM `Trans`
) B ON C.`UserID` = B.`From`
SET `Bal` = A.`LSC` - B.`LSC`;
and this is not workink :\
when i just do 1 inner join and run the query twice once to A and second to be it work but i want to do it in one query ...
UPDATE BA C
INNER JOIN
(
SELECT SUM(`Amount`) AS `LSC`,`To` FROM `Trans`
) A ON C.`UserID` = A.`To`
SET `Bal` = A.`LSC`; // Work

Store the results of a sub-query for use in multiple joins

I have the following MySQL query, which produces the result I want:
SELECT
`l`.`status`,
`l`.`acquired_by`, `a`.`name` AS 'acquired_by_name',
`l`.`researcher`, `r`.`name` AS 'researcher_name',
`l`.`surveyor`, `s`.`name` AS 'surveyor_name'
FROM `leads` `l`
LEFT JOIN (
SELECT '0' AS 'id', 'Unassigned' AS 'name'
UNION ALL
SELECT `id`, `name`
FROM `web_users`
) `r` ON `r`.`id` = `l`.`researcher`
LEFT JOIN (
SELECT '0' AS 'id', 'Unassigned' AS 'name'
UNION ALL
SELECT `id`, `name`
FROM `web_users`
) `s` ON `s`.`id` = `l`.`surveyor`
LEFT JOIN (
SELECT '0' AS 'id', 'Unassigned' AS 'name'
UNION ALL
SELECT `id`, `name`
FROM `web_users`
) `a` ON `a`.`id` = `l`.`acquired_by`
WHERE `l`.`id` = 566
But as you can see, it has the same sub-query in it three times. Is there any way to execute this query once and store the result, so I can LEFT JOIN with the cached results instead of executing the same query three times?
I have tried storing it in a variable:
SET #usercache = (
SELECT '0' AS 'id', 'Unassigned' AS 'name'
UNION ALL
SELECT `id`, `name`
FROM `web_users`
)
...but this gives me an error:
1241 - Operand should contain 1 column(s)
...and some Googling on this error has left me none the wiser.
Does anyone know how I can make this query more efficient? Or am I just worrying about something that doesn't matter anyway?
I am using PHP/MySQLi if it makes any difference.
Do you really need the subqueries? How about this:
SELECT
`l`.`status`,
`l`.`acquired_by`, COALESCE(`a`.`name`, 'Unassigned') AS 'acquired_by_name',
`l`.`researcher`, COALESCE(`r`.`name`, 'Unassigned') AS 'researcher_name',
`l`.`surveyor`, COALESCE(`s`.`name`, 'Unassigned') AS 'surveyor_name'
FROM `leads` `l`
LEFT JOIN `web_users` `r` ON `r`.`id` = `l`.`researcher`
LEFT JOIN `web_users` `s` ON `s`.`id` = `l`.`surveyor`
LEFT JOIN `web_users` `a` ON `a`.`id` = `l`.`acquired_by`
WHERE `l`.`id` = 566
you cannot run it once - you are actually using it three times to get three different results...