PHP Heatmap - Large Value difference - mysql

Hi I have this Query and I'm getting an empty result, Anyone see anything obviously wrong with this?
SET SQL_BIG_SELECTS=1;
SELECT sector, SUM((fleetnow)+(fleetsoon)) AS Count
FROM AEDatabase
INNER JOIN AEPlayer AS Own ON AEDatabase.owner = Own.id
INNER JOIN AEPlayer AS Occ ON AEDatabase.occer = Occ.id
WHERE Galaxy='L49' AND (Own.guild='1085' OR Occ.guild='1085')
GROUP BY sector
Specific message from MySQL is:
"MySQL returned an empty result set (i.e. zero rows). ( Query took 0.4441 sec )"
Thanks for any help anyone can give.

If SQL request is composed correctly according to your business logic, and it returns no data it means, that either AEPlayer doesn't contain related data or AEDatabase doesn't contain any data related to Galaxy='L49'
You should separate all components of your request to determine what exactly collapses the result set.

Related

Problems with a LEFT JOIN

I'm trying to do a left join in two tables, the principal one is a table with production orders and the other one contains the quantity of defective material in those production orders. It is possible to have more than one different type of defect in one production order, so that means more than one register in the second table for one production order. The relations between table are the field production order, machine, production phase, article and enterprise:
SELECT PM.FECHA_FABRICACION,
--TRUNC(PM.FECHA_FABRICACION) AS FECHA,
PM.ORDEN_DE_FABRICACION,
PM.CODIGO_FAMILIA,
PM.CODIGO_ARTICULO,
PM.COD_MAQUINA,
DECODE (PM.COD_MAQUINA,'AN001','ANODIZADO', 'GR001','ANODIZADO', 'ES001','ANODIZADO','PU001', 'ANODIZADO', 'ZZ141', 'ANODIZADO', PM.COD_MAQUINA) AS MAQUINA_PARTE,
PM.DESC_MAQUINA,
PM.CANTIDAD_ACEPTADA,
PM.M2_ACEPTADOS,
PM.M2_CONPEPTO,
PM.M2_TOTAL,
PM.M2_EXT,
PM.KILOS_ACEPTADOS,
PM.BARRAS_ACEPTADAS,
PM.FASE_REALIZADA,
PR.CODIGO_DEFECTO,
PR.CANTIDAD_RECHAZADA,
PR.LONGITUD,
PR.KILOS_RECHAZADOS,
PR.OBSERVACIONES
FROM ST_VW_PRODUCCION_MAQUINAS PM
LEFT JOIN P_INFO_RECHAZOS PR
ON PM.CODIGO_EMPRESA = PR.CODIGO_EMPRESA
AND PM.ORDEN_DE_FABRICACION = PR.ORDEN_DE_FABRICACION
AND PM.CODIGO_ARTICULO = PR.CODIGO_ARTICULO
AND PM.COD_MAQUINA = PR.CODIGO_MAQUINA
AND PM.FASE_REALIZADA = PR.FASE
AND PM.CODIGO_EMPRESA = '01'
AND PM.FECHA_FABRICACION > TO_DATE('04/07/2022 00:00:00', 'DD/MM/YYYY HH24:MI:SS')
--AND TRUNC(PM.FECHA_FABRICACION) = TRUNC(PR.FECHA_RECHAZO);
However it's not working
If you are specifically looking for rejections, you dont need a LEFT JOIN, but a normal INNER JOIN, meaning you ONLY WANT to see those projects where at least one, or more, rejections had occurred.
The query itself looks ok otherwise, just get rid of the LEFT clause of left join.
As for the function DECODE, that is using PM.COD_MAQUINA at both the begin and end of the list of codes. Dont know if that was intentional.
For date filtering, if you are only looking for a specific date without regard to any time portion, you could change it to YYYY-MM-DD format without using the TO_DATE() construct as in
AND PM.FECHA_FABRICACION > '2022-07-04'
If you still are getting errors, please EDIT your post and provide what the error message is.
To explain further, you are using a LEFT JOIN, which is a type of outer join. An outer join means that all the results from one side that don't match will still be displayed, and will just be matched to null. In your case, production orders that aren't defective will be listed.
However, it seems that you want to only display results that match on both sides (production orders that do have defects). When you just JOIN then you will have the result you want.
Here's a helpful diagram

nested "select " query in mysql

hi i am executing nested "select" query in mysql .
the query is
SELECT `btitle` FROM `backlog` WHERE `bid` in (SELECT `abacklog_id` FROM `asprint` WHERE `aid`=184 )
I am not getting expected answer by the above query. If I execute:
SELECT abacklog_id FROM asprint WHERE aid=184
separately
I will get abacklog_id as 42,43,44,45;
So if again I execute:
SELECT `btitle` FROM `backlog` WHERE `bid` in(42,43,44,45)
I will get btitle as scrum1 scrum2 scrum3 msoffice
But if I combine those queries I will get only scrum1 remaining 3 atitle will not get.
You Can Try As Like Following...
SELECT `age_backlog`.`ab_title` FROM `age_backlog` LEFT JOIN `age_sprint` ON `age_backlog`.`ab_id` = `age_sprint`.`as_backlog_id` WHERE `age_sprint`.`as_id` = 184
By using this query you will get result with loop . You will be able to get all result with same by place with comma separated by using IMPLODE function ..
May it will be helpful for you... If you get any error , Please inform me...
What you did is to store comma separated values in age_sprint.as_backlog_id, right?
Your query actually becomes
SELECT `ab_title` FROM `age_backlog` WHERE `ab_id` IN ('42,43,44,45')
Note the ' in the IN() function. You don't get separate numbers, you get one string.
Now, when you do
SELECT CAST('42,43,44,45' AS SIGNED)
which basically is the implicit cast MySQL does, the result is 42. That's why you just get scrum1 as result.
You can search for dozens of answers to this problem here on SO.
You should never ever store comma separated values in a database. It violates the first normal form. In most cases databases are in third normal form or BCNF or even higher. Lower normal forms are just used in some special cases to get the most performance, usually for reporting issues. Not for actually working with data. You want 1 row for every as_backlog_id.
Again, your primary goal should be to get a better database design, not to write some crazy functions to get each comma separated number out of the field.

Why isn't my SQL LEFT JOIN query working?

It is returning 0 rows when there should be some results.
This is my first attempt at using JOIN but from what I've read this looks pretty much right, right?
"SELECT pending.paymentid, pending.date, pending.ip, pending.payer, pending.type, pending.amount, pending.method, pending.institution, payment.number, _uploads_log.log_filename
FROM pending
LEFT JOIN _uploads_log
ON pending.paymentid='".$_GET['vnum']."'
AND _uploads_log.linkid = pending.paymentid"
I need to return the specified values from each table where both pending.paymentid and _uploads_log.log_filename are equal to $_GET['vnum]
What is the correct way to do this? Why am I not getting any results?
If someone more experienced than me could point me in the right direction I would be much obliged.
EDIT
For pending the primary key is paymentid, for _uploads_log the primary is a col called log_id and log_filename is listed as index.
Try this
SELECT pending.paymentid,
pending.date,
pending.ip,
pending.payer,
pending.type,
pending.amount,
pending.method,
pending.institution,
payment.number,
_uploads_log.log_filename
FROM pending
LEFT JOIN _uploads_log
ON _uploads_log.linkid = pending.paymentid
WHERE _uploads_log.log_filename = '" . $_GET['vnum'] . "'
Your current query is vulnerable with SQL Injection. Please take time to read the article below.
Best way to prevent SQL injection in PHP?
The ON clause only should have the condition to link the two tables especially if it is LEFT JOIN. The WHERE clause then has the actual condition. Otherwise you will get nothing if there is no corresponding entry in _uploads_log. It also is more easy to read in my opinion.
As another remark. It is always better to work with bind parameters to avoid SQL injection.

MySQL Error 1172 - Result consisted of more than one row

I'm getting this error from MySQL when running a query inside a stored procedure:
Error Code: 1172
Result consisted of more than one row
I understand the error: I'm doing a SELECT (...) INTO (var list), and thus the query is required to return a single row. When I use LIMIT 1 or SELECT DISTINCT, the error goes away.
However: when I run the original query manually (without LIMIT or DISTINCT), it does return a single row. So I'm suspecting I may have bumped into a MySQL bug. Does anyone know what could be happening?
EDIT
I'm posting the SQL as requested. Everything that starts with an underscore is a variable declared earlier inside the procedure. When I test it, I'm replacing _cd_pai_vc with the ID for the record that is causing the problem.
SELECT a.valor, IFNULL(p.valor, 0), fn_cd2alias(ra.cd_registro), fn_cd2alias(IFNULL(p.valor,0))
INTO _valor, _cd_pai_vc, _alias_verbete, _alias_pai
FROM dados_registros ra
INNER JOIN dados_varchar255 a
ON a.cd_registro = ra.cd_registro
AND a.fl_excluido = 0
AND a.alias = 'vc-verbetes-termo'
LEFT OUTER JOIN dados_registros rp
INNER JOIN dados_int p
ON p.cd_registro = rp.cd_registro
AND p.fl_excluido = 0
AND p.alias = 'vc-remissoes-termo referenciado'
INNER JOIN dados_int pt
ON pt.cd_registro = rp.cd_registro
AND pt.fl_excluido = 0
AND pt.alias = 'vc-remissoes-tipo remissao'
AND fn_cd2alias(pt.valor) = 'hierarquica'
ON ra.cd_registro = rp.cd_entidade
AND rp.fl_excluido = 0
AND fn_cd2alias(rp.cd_modulo) = 'vc-remissoes'
WHERE ra.cd_registro = _cd_pai_vc
AND ra.fl_excluido = 0;
I had the similiar issue and when I put table alias it worked like a charm.
SELECT t.tax_amount,t.tax_percentage FROM nepse_tax t
I had this problem and found it went away when I used both table name and column name in select statements, even simple ones.
The issue i had was IN parameter and the column name both were same so altered IN parameter name and it worked
I have experienced the same error in mysql.
MySQL Error 1172 - Result consisted of more than one row
Then I saw the question:
mysql stored procedure error (1172, 'Result consisted of more than one row')
But it was not I meant to ask. LIMIT 1;-wasn't up to my expectation. It will just return the first row for all the case.
Then I started looking at this one deeply and now I got the solution.
This case happend because the code for stored procedure returns multiple rows and that was because I had many extra spaces and tab characters in my code[the code I wrote for stored procedure] and when I removed them with just one/two appropriate tab chars- it was just like a flying machine.
I don't know if it is the same case that you are experienced with. Anyway give a try.
Thank you.
I had the same problem, the solution by Nava Bogatee worked like a charm,
below is a part of the procedure
select attendance
into brb
from Stud
where Rno like rno;
This didn't work I have no idea why.
Then I changed this to
select t.attendance
into brb
from Stud t
where t.Rno like rno;
and it worked.
I guess due to some reason the Rno column is returning all the values in the table, that is why the multiple row error.

Can we control LINQ expression order with Skip(), Take() and OrderBy()

I'm using LINQ to Entities to display paged results. But I'm having issues with the combination of Skip(), Take() and OrderBy() calls.
Everything works fine, except that OrderBy() is assigned too late. It's executed after result set has been cut down by Skip() and Take().
So each page of results has items in order. But ordering is done on a page handful of data instead of ordering of the whole set and then limiting those records with Skip() and Take().
How do I set precedence with these statements?
My example (simplified)
var query = ctx.EntitySet.Where(/* filter */).OrderByDescending(e => e.ChangedDate);
int total = query.Count();
var result = query.Skip(n).Take(x).ToList();
One possible (but a bad) solution
One possible solution would be to apply clustered index to order by column, but this column changes frequently, which would slow database performance on inserts and updates. And I really don't want to do that.
EDIT
I ran ToTraceString() on my query where we can actually see when order by is applied to the result set. Unfortunately at the end. :(
SELECT
-- columns
FROM (SELECT
-- columns
FROM (SELECT -- columns
FROM ( SELECT
-- columns
FROM table1 AS Extent1
WHERE EXISTS (SELECT
-- single constant column
FROM table2 AS Extent2
WHERE (Extent1.ID = Extent2.ID) AND (Extent2.userId = :p__linq__4)
)
) AS Project2
limit 0,10 ) AS Limit1
LEFT OUTER JOIN (SELECT
-- columns
FROM table2 AS Extent3 ) AS Project3 ON Limit1.ID = Project3.ID
UNION ALL
SELECT
-- columns
FROM (SELECT -- columns
FROM ( SELECT
-- columns
FROM table1 AS Extent4
WHERE EXISTS (SELECT
-- single constant column
FROM table2 AS Extent5
WHERE (Extent4.ID = Extent5.ID) AND (Extent5.userId = :p__linq__4)
)
) AS Project6
limit 0,10 ) AS Limit2
INNER JOIN table3 AS Extent6 ON Limit2.ID = Extent6.ID) AS UnionAll1
ORDER BY UnionAll1.ChangedDate DESC, UnionAll1.ID ASC, UnionAll1.C1 ASC
My workaround solution
I've managed to workaround this problem. Don't get me wrong here. I haven't solved precedence issue as of yet, but I've mitigated it.
What I did?
This is the code I've used until I get an answer from Devart. If they won't be able to overcome this issue I'll have to use this code in the end.
// get ordered list of IDs
List<int> ids = ctx.MyEntitySet
.Include(/* Related entity set that is needed in where clause */)
.Where(/* filter */)
.OrderByDescending(e => e.ChangedDate)
.Select(e => e.Id)
.ToList();
// get total count
int total = ids.Count;
if (total > 0)
{
// get a single page of results
List<MyEntity> result = ctx.MyEntitySet
.Include(/* related entity set (as described above) */)
.Include(/* additional entity set that's neede in end results */)
.Where(string.Format("it.Id in {{{0}}}", string.Join(",", ids.ConvertAll(id => id.ToString()).Skip(pageSize * currentPageIndex).Take(pageSize).ToArray())))
.OrderByDescending(e => e.ChangedOn)
.ToList();
}
First of all I'm getting ordered IDs of my entities. Getting only IDs is well performant even with larger set of data. MySql query is quite simple and performs really well. In the second part I partition these IDs and use them to get actual entity instances.
Thinking of it, this should perform even better than the way I was doing it at the beginning (as described in my question), because getting total count is much much quicker due to simplified query. The second part is practically very very similar, except that my entities are returned rather by their IDs instead of partitioned using Skip and Take...
Hopefully someone may find this solution helpful.
I haven't worked directly with Linq to Entities, but it should have a way to hook specific stored procedures into certain locations when needed. (Linq to SQL did.) If so, you could turn this query into a stored procedure, doing exacly what is required, and doing it efficiently.
Assuming from you comment the persisting the values in a List is not acceptable:
There's no way to completely minimize the iterations, as you intended (and as I would have tried too, living in hope). Cutting the iterations down by one would be nice. Is it possible to just get the Count once and cache/session it? Then you could:
int total = ctx.EntitySet.Count; // Hopefully you can not repeat doing this.
var result = ctx.EntitySet.Where(/* filter */).OrderBy(/* expression */).Skip(n).Take(x).ToList();
Hopefully you can cache the Count somehow, or avoid needing it every time. Even if you can't, this is the best you can do.
Could you please create a sample illusrating the problem and send it to us (support * devart * com, subject "EF: Skip, Take, OrderBy")?
Hope we will be able to help you.
You can also contact us using our forums or contact form.
Are you absolutely certain the ordering is off? What does the SQL look like?
Can you reorder your code as follows and post the output?
// Redefine your queries.
var query = ctx.EntitySet.Where(/* filter */).OrderBy(e => e.ChangedDate);
var skipped = query.Skip(n).Take(x);
// let's look at the SQL, shall we?
var querySQL = query.ToTraceString();
var skippedSQL = skipped.ToTraceString();
// actual execution of the queries...
int total = query.Count();
var result = skipped.ToList();
Edit:
I'm absolutely certain. You can check my "edit" to see trace result of my query with skipped trace result that is imperative in this case. Count is not really important.
Yeah, I see it. Wow, that's a stumper. Might even be an outright bug. I note you're not using SQL Server... what DB are you using? Looks like it might be MySQl.
One way:
var query = ctx.EntitySet.Where(/* filter */).OrderBy(/* expression */).ToList();
int total = query.Count;
var result = query.Skip(n).Take(x).ToList();
Convert it to a List before skipping. It's not too efficient, mind you...