mysql query return null row [duplicate] - mysql

This question already has answers here:
SELECT SUM returns a row when there are no records
(8 answers)
Closed 7 years ago.
i want to execute this query but it return null row when the table empty. it's working when SUM(products.sale_price)/COUNT(orders.id) AS avg_price_rang
is not in the query
SELECT
products.brand_id,
(SELECT
category_brands.name
FROM
category_brands
WHERE
category_brands.id=products.brand_id
) AS brand,
products.material_id,
(SELECT
category_materials.material
FROM
category_materials
WHERE
category_materials.id=products.material_id
) AS material,
orders.color_code,
SUM(products.sale_price)/COUNT(orders.id) AS avg_price_rang
FROM
orders
INNER JOIN
products
ON
orders.prodcut_id = products.id

I think it's missing GROUP BY products.brand_id.

SELECTing SUM when there are no rows causess a row of all NULLs to be returned.
MySQL 5.5 Reference Manual
12.17.1 GROUP BY (Aggregate) Functions
If you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows. For more information, see Section 12.17.3, “MySQL Handling of GROUP BY”.
Use:
query
HAVING avg_price_rang IS NOT NULL
SELECT * FROM (
query
) dummy
WHERE avg_price_rang IS NOT NULL

Related

How do I replace NULL values with 'N/A' in SQL? [duplicate]

This question already has answers here:
MySql Query Replace NULL with Empty String in Select
(10 answers)
Closed 4 months ago.
I am looking to replace the NULL values that occur as a result of a SQL JOIN statement, with 'N/A'.
I have tried to set the default value of both related columns from both tables to N/A, however, every time I execute the SQL JOIN statement, I still receive NULL values.
The two tables I have are the clients and Medical_Aid tables, which I have connected using a foreign key called Reg_No. Below is my sql join query
SELECT
clients.Id_Number,
clients.Medical_No,
medical_aid.Name AS Medical_Aid,
clients.First_Name,
clients.Last_Name,
clients.Age,
clients.Gender,
clients.Email,
clients.Telephone
FROM
clients
LEFT OUTER JOIN medical_aid ON clients.Reg_No = medical_aid.Reg_No;
I have tried to set the default value of the Medical_No and Medical_Name as 'N/A' but every time I execute a JOIN statement, NULL values are returned on the Medical_Name column only
Therefore, I am expecting the JOIN Statement to return 'N/A' for both the Medical_No and medical_AidName
SELECT
clients.Id_Number,
ISNULL(clients.Medical_No,'N/A'),
ISNULL(medical_aid.Name, 'N/A') AS Medical_Aid,
clients.First_Name,
clients.Last_Name,
clients.Age,
clients.Gender,
clients.Email,
clients.Telephone
FROM
clients
LEFT OUTER JOIN medical_aid ON clients.Reg_No = medical_aid.Reg_No;
For the values from the medial_aid table you can use the IsNull() function to replace a NULL with a different value:
IsNull(medical_aid.Name, 'N/A') AS Medical_Aid
If you want to also replace another field from the clients table when no record is found in the medical_aid table, you may need to use a CASE statement:
CASE WHEN medical_aid.Reg_No is null THEN 'N/A' else clients.Medical_No END AS Medical_No
This statement says that when medical_aid.Reg_No is NULL (since there was no record from the medical_aid found to join to the clients table) then output 'N/A', otherwise output clients.Medical_No.

mysql query return not right when i use decimal [duplicate]

This question already has answers here:
Return 0 if field is null in MySQL
(5 answers)
Closed 6 years ago.
select sum(charge) as charges from chargelist
If there's no record in chargelist, $query->num_rows() returns 1, not 0, run this query in phpmyadmin, result is following
Please help me.
Well this is ANSI SQL Behaviour as shown in this SO answer.
If you want to return empty record set you can check in outer query
select * from (select sum(charge) as charges from chargelist ) As tmp
where charges is not null

Error updating record with sub query [duplicate]

This question already has answers here:
MySQL Error 1093 - Can't specify target table for update in FROM clause
(16 answers)
Closed 2 years ago.
I am updating record on the base of sub query but it giving me error
you can't specify target table for update in from clause
my query is
UPDATE paymentinfo set customer_id =
(
SELECT transation.transactionid
FROM paymenttransaction AS transation
LEFT JOIN paymentinfo as payment
ON (transation.paymentinfoid=payment.paymentinfoid)
where payment.hash="0b576d33c57484692131471a847eab7c"
)
WHERE hash="0b576d33c57484692131471a847eab7c"
where am i wrong and what will be perfect solution for that problem
You are updating the table 'paymentinfo' also at same time you are using this table for selection in subquery .
Please break this query in two parts and it will work .
I think it is simplest (in your case) to use the double subquery method:
UPDATE paymentinfo
SET customer_id = (SELECT transactionid
FROM (SELECT t.transactionid
FROM paymenttransaction pt LEFT JOIN
paymentinfo pi
ON t.paymentinfoid = pi.paymentinfoid
WHERE p.hash = '0b576d33c57484692131471a847eab7c'
) t
)
WHERE hash = '0b576d33c57484692131471a847eab7c';
Usually, you want to switch these to use JOIN, but I think that is a bit complicated in this case.

Find rows in a MySQL query where the index values must all exist [duplicate]

This question already has answers here:
How to return rows that have the same column values in MySql
(3 answers)
Closed 6 years ago.
I am trying to find the rows that exist inside an index, however, my results keep coming up null even though there are rows that match my index. Is there something wrong with the logic of my query?
Here is my test query:
SELECT `the_products` . *
FROM `the_products`
INNER JOIN `producttypes_index` ON `producttypes_index`.`the_product_id` = `the_products`.`id`
AND `producttypes_index`.`type_id` = '1'
INNER JOIN `producthashtags_index` ON `producthashtags_index`.`the_product_id` = `the_products`.`id`
WHERE
`producthashtags_index`.`producthashtag_id`
IN ('41')
AND
`producthashtags_index`.`producthashtag_id`
IN ('42')
AND
`producthashtags_index`.`producthashtag_id`
IN ('6')
ORDER BY updated_at DESC
Here you can see the_product_id 54433 exists inside the index table producthashtags_index using query:
SELECT *
FROM `producthashtags_index`
WHERE `the_product_id` =54433
Results:
id producthashtag_id the_product_id
25433 6 54433
25434 41 54433
25435 42 54433
Then you can see it also exists inside the index table producttypes_index using query:
SELECT *
FROM `producttypes_index`
WHERE `the_product_id` =54433
Results:
type_id the_product_id
1 54433
Remove
AND `producttypes_index`.`type_id` = '1'
you can also optimaze your code by making the 3 IN`s into one like this:
AND `producthashtags_index`.`producthashtag_id` IN('42','41','6')

mysql only insert row if value does not exists [duplicate]

This question already has answers here:
MySQL Conditional Insert
(13 answers)
Closed 8 years ago.
A complex mysql question! I only want to insert the last value (with the zero values) if there is no other row with value 1420070400, but i cant put an index on the row (so i can use on duplicate key). Is there a way to do this on an other way?
INSERT INTO data_prijzen_advertentie (
`ID_advertentie`,`jaar`,`rijnr`,`status_prijs`,`datum_dag`,`timestamp_dag`,
`prijs_maand`,`prijs_week`,`prijs_midweek`,`prijs_langweekend`,`prijs_weekend`,
`prijs_dag`,`prijs_ochtend`,`prijs_middag`
)
VALUES
(100,2014,1,1,'12-05-2014',1399852800,0,100,0,75,0,0,0,0),
(100,2014,2,1,'23-05-2014',1400803200,0,75,0,101,0,0,0,0),
(100,2014,3,1,'30-05-2014',1401408000,0,100,0,75,0,0,0,0),
(100,2014,4,1,'01-01-2015',1420070400,0,0,0,0,0,0,0,0)
ON DUPLICATE KEY UPDATE
status_prijs = VALUES(status_prijs), datum_dag = VALUES(datum_dag),
timestamp_dag = VALUES(timestamp_dag), prijs_maand = VALUES(prijs_maand),
prijs_week = VALUES(prijs_week), prijs_midweek = VALUES(prijs_midweek),
prijs_langweekend = VALUES(prijs_langweekend), prijs_weekend = VALUES(prijs_weekend),
prijs_dag = VALUES(prijs_dag), prijs_ochtend = VALUES(prijs_ochtend),
prijs_middag = VALUES(prijs_middag);
One way to do this is to use a SELECT in place of the VALUES clause. Use the SELECT statement to return the rows you want inserted. For example:
SELECT 100 AS a,2014 AS b,1 AS c,1 AS d,'12-05-2014' AS e
,1399852800 AS timestamp_dag
,0 AS g,100 AS h,0 AS i,75 AS j,0 AS k,0 AS l,0 AS m,0 AS n
UNION ALL
SELECT 100,2014,2,1,'23-05-2014',1400803200,0,75,0,101,0,0,0,0
UNION ALL
SELECT 100,2014,3,1,'30-05-2014',1401408000,0,100,0,75,0,0,0,0
UNION ALL
SELECT 100,2014,4,1,'01-01-2015',1420070400,0,0,0,0,0,0,0,0
With a SELECT, it's also possible to check for rows that already exist in the table. You can use that query above as an inline view (i.e. wrap that query in parens and assign an alias for the derived table) and write a SELECT against it (like it was a table), and use a NOT EXISTS predicate or an anti-join pattern to suppress the return of rows where a "matching" row already exists in the target table. For example:
SELECT s.*
FROM ( SELECT 100 AS a,2014 AS b,1 AS c,1 AS d,'12-05-2014' AS e
,1399852800 AS timestamp_dag
,0 AS g,100 AS h,0 AS i,75 AS j,0 AS k,0 AS l,0 AS m,0 AS n
UNION ALL
SELECT 100,2014,2,1,'23-05-2014',1400803200,0,75,0,101,0,0,0,0
UNION ALL
SELECT 100,2014,3,1,'30-05-2014',1401408000,0,100,0,75,0,0,0,0
UNION ALL
SELECT 100,2014,4,1,'01-01-2015',1420070400,0,0,0,0,0,0,0,0
) s
LEFT
JOIN data_prijzen_advertentie t
ON t.timestamp_dag = s.timestamp_dag
WHERE t.timestamp_dag IS NULL
(NOTE: the LEFT JOIN operation returns all rows from the derived table s, along with matching rows from t; the "trick" is to use a WHERE clause that eliminates all rows that found a match, so we are left with rows from s that didn't have a matching row in t. The same thing could be achieved with a NOT EXISTS predicate with a correlated subquery.)
It may be necessary to wrap this query in parens and reference it as an inline view (so it is again, a derived table) to avoid a mutating table issue/error. For example:
SELECT r.*
FROM (
SELECT s.*
FROM (
SELECT 100 AS a,2014 AS b,1 AS c,1 AS d,'12-05-2014' AS e
,1399852800 AS timestamp_dag
,0 AS g,100 AS h,0 AS i,75 AS j,0 AS k,0 AS l,0 AS m,0 AS n
UNION ALL
SELECT 100,2014,2,1,'23-05-2014',1400803200,0,75,0,101,0,0,0,0
UNION ALL
SELECT 100,2014,3,1,'30-05-2014',1401408000,0,100,0,75,0,0,0,0
UNION ALL
SELECT 100,2014,4,1,'01-01-2015',1420070400,0,0,0,0,0,0,0,0
) s
LEFT
JOIN data_prijzen_advertentie t
ON t.timestamp_dag = s.timestamp_dag
WHERE t.timestamp_dag IS NULL
) r
Once you have a query working that returns the rows you want (excluding rows where a matching row already exists in the target table), you can substitute the VALUES clause in the INSERT statement with the query.
Note: this only checks for existence of rows already in the table when the query runs. This doesn't check the resultset returned by the query, to see if there are two (or more) rows with the timestamp_dag value.