sql query giving weird results - mysql

why is this query giving weird results..
SELECT max(greatest(home_team_total,away_team_total)) AS max_team_score, id
FROM `match`
WHERE id IN (1,2,3,4,5)
while
SELECT greatest(home_team_total,away_team_total) AS max_team_score, id
FROM `match`
WHERE id IN (1,2,3,4,5)
ORDER BY max_team_score DESC
LIMIT 1
gives correct result..
The max value is correct only in both cases but id of match is wrong in first case..

It's because you're including the id field in the SELECT clause. Which id do you want? I get that you might want the one associated with the max row, but there could be multiple ones, and what if you were also returning min(greatest(home_team_total,away_team_total))?
The second query is the one you want for this problem.
Editing to make it a little clearer:
Your query is equivalent to:
SELECT max(greatest(home_team_total,away_team_total)) AS max_team_score, ANY(id)
FROM `match`
WHERE id IN (1,2,3,4,5)
Look at http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html
It says: "The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate."

If you do want the first query to work, you have to change it to something like the following:
SELECT greatest(home_team_total,away_team_total) AS max_team_score, id
FROM match
WHERE greatest(home_team_total,away_team_total) =
(
SELECT max(greatest(home_team_total,away_team_total)) FROM match
)
Note that you can have more than one row in the result, so I would prefer this solution to the "LIMIT 1" alternative.

Related

Select multiple fields, and count only one

I want to count the ugyfel_email field in this select.
If i run it, i didnt get errors, but from the table records, it will only show one row.
What am i doing wrong?
SELECT id,ugyfel_nev,ugyfel_email,parkolo_tipus,ugyfel_tel,rendszam,erkezes_datum,
erkezes_ideje,allapot, utasok, COUNT(ugyfel_nev) AS ennyiszer FROM foglalas WHERE allapot = 'Feldolgozva' ORDER BY id DESC
In order to count a column, you need to reference it to some other column. By that I mean it needs to represent something. In your query I assume you want to count how many ugyfel_emain there is for a specific allpot, this will look like:
SELECT COUNT(ugyfel_nev), COUNT(ugyfel_email)
FROM foglalas
GROUP BY allapot
HAVING allapot = 'Feldolgozva' # if you want only for this
ORDER BY id DESC

Limiting the count query in MySQL?

I am trying to do a simple test where I'm pulling from a table the information of a specific part number as such:
SELECT *
FROM table_name
WHERE part_no IN ('abc123')
This returns 25 rows. Now I want to count the number that meet the "accepted" condition in a specific column but the result is limited to only the 10 most recent. My approach is to write it as follows:
Select Count(*)
FROM table_name
WHERE part_no IN ('abc123') AND lot IN ('accepted')
ORDER BY date DESC
LIMIT 10
I'm having a hard time to get the ORDER BY and LIMIT operations to work. I could use help just getting it to limit appropriately, and I can figure out the rest from there.
Edit: I understand that the operations are happening on the COUNT which only returns one row with a value; but I put the second clip to show where I am stuck in my thought process.
Your query SELECT Count(*) FROM ... will always return exactly one row.
It's not 100% clear what exactly you want to do, but if you want to know how many of the last 10 have been accepted, you could use a subquery - something like:
SELECT COUNT(*) FROM (
SELECT lot
FROM table_name
WHERE part_no IN ('abc123')
ORDER BY date DESC
LIMIT 10
)
WHERE lot IN ('accepted')
The inner query will return the 10 most recent rows for part abc123, then the outer query will count the accepted ones.
There are also other solution (for example, you could have the inner query output a field that is 0 when the part is not accepted and 1 when the part is accepted, then take the sum). Depending on which exact dialect/database you are using, you may also have more elegant options.
Select count returns ONE ROW therefore the ORDER BY and the LIMIT will not work on the results

Mysql DISTINCT with more than one column (remove duplicates)

My database is called: (training_session)
I try to print out some information from my data, but I do not want to have any duplicates. I do get it somehow, may someone tell me what I do wrong?
SELECT DISTINCT athlete_id AND duration FROM training_session
SELECT DISTINCT athlete_id, duration FROM training_session
It works perfectly if i use only one column, but when I add another. it does not work.
I think you misunderstood the use of DISTINCT.
There is big difference between using DISTINCT and GROUP BY.
Both have some sort of goal, but they have different purpose.
You use DISTINCT if you want to show a series of columns and never repeat. That means you dont care about calculations or group function aggregates. DISTINCT will show different RESULTS if you keep adding more columns in your SELECT (if the table has many columns)
You use GROUP BY if you want to show "distinctively" on a certain selected columns and you use group function to calculate the data related to it. Therefore you use GROUP BY if you want to use group functions.
Please check group functions you can use in this link.
https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html
EDIT 1:
It seems like you are trying to get the "latest" of a certain athlete, I'll assume the current scenario if there is no ID.
Here is my alternate solution:
SELECT a.athlete_id ,
( SELECT b.duration
FROM training_session as b
WHERE b.athlete_id = a.athlete_id -- connect
ORDER BY [latest column to sort] DESC
LIMIT 1
) last_duration
FROM training_session as a
GROUP BY a.athlete_id
ORDER BY a.athlete_id
This syntax is called IN-SELECT subquery. With the help of LIMIT 1, it shows the topmost record. In-select subquery must have 1 record to return or else it shows error.
MySQL's DISTINCT clause is used to filter out duplicate recordsets.
If your query was SELECT DISTINCT athlete_id FROM training_session then your output would be:
athlete_id
----------
1
2
3
4
5
6
As soon as you add another column to your query (in your example, the column called duration) then each record resulting from your query are unique, hence the results you're getting. In other words the query is working correctly.

match results generated by SQL WHERE IN CLAUSE

let's see I have a simple table like this:
name id
tom 1
jerry 2
... ...
And from the outside, I got a list contains the names (tom, jerry, kettie...)
I am trying to use WHERE IN clause to retrieve the id based on the name list.
I can do
SELECT id FROM mySimpleTable where name in ('tom','jerry','kettie');
So just iterate the name list and generate the contents in the parentheses.
This works, but the results is not in the input order, for example, the input is tom, jerry, kettie, the expected the result is 1,2,3, however, the output actually could be in any order.
Then how can I modify the SQL clause to make sure I get my input and output matched so that I can do the following process accrordingly. I heard JOIN may help in this situation.
SELECT id
FROM mySimpleTable
where name in ('tom','jerry','kettie')
order by field(name, 'tom','jerry','kettie')
I heard JOIN may help in this situation.
Yes it can help:
SELECT m.id
FROM mySimpleTable m
JOIN (
SELECT 'tom' AS name, 1 AS orderNum
UNION ALL
SELECT 'jerry' AS name, 2 AS orderNum
UNION ALL
SELECT 'kettie' AS name, 3 AS orderNum
) AS sub
ON m.name = sub.name
ORDER BY sub.orderNum ASC;
SqlFiddleDemo
This solution can be also used in different RDBMS. field is MySQL specific.
How it works:
Create derived table/subquery with values you need to check and ordering column
JOIN will return only rows that correspond each other based on name
ORDER BY column you've added in subquery
just select id,name from table_a where name in ('tom','jerry','happy') , you will have the combination of the input name and output id.
this entirely depends on where you're getting the list for your "in" clause.
if it's from somewhere on the outside, you probably should first turn the list into a temp table, adding an id column that indicates the order (see this answer for a start on how to do that) - and then do an inner join with it.
I did try to run your SQL query, and me for one did get the resultant output in the same order as that of the input. Well, but still it isn't necessary it would happen the same way every time, so the best way to arrange your output in a particular hierarchy is to use the ORDER BY clause. The syntax would be:
SELECT column_name
FROM table_name
WHERE conditions
ORDER BY column_name;
So in your case, the query would read as:
SELECT id
FROM mysimpletable
WHERE name
IN('tom','jerry','kettie'....)
ORDER BY id;
You can get more help with MySQL concepts here for further information.
Select
id
from mySimpleTable
where name in ('tom','jerry','kettie')
Order by id

How to get count of rows returned from nested and WHERE IN used query in MySQL?

SELECT kullaniciNick,
kullaniciAdi,
kullaniciSoyadi
FROM panelkullanicilari
WHERE id IN
(SELECT user_id
FROM proje_ekip
WHERE proje_id=11)
ORDER BY kullaniciSoyadi
at the query i need the count of rows to check if it is over 6 or less.
When i used the COUNT(*) i got an error message. That said it must used with GROUP BY.
Thank you.
Try this:
SELECT kullaniciNick,
kullaniciAdi,
kullaniciSoyadi,
count(*) -- Added this line
FROM panelkullanicilari
WHERE id IN
(SELECT user_id
FROM proje_ekip
WHERE proje_id=11)
GROUP BY 1,2,3 -- Added this line
ORDER BY kullaniciSoyadi
You can't have a result, and it's size in one query.
Use 2 queries. First one will give you the size of result and second one will be the result. The First query, should be like this:
SELECT count(*)
FROM panelkullanicilari
WHERE id IN
(SELECT user_id
FROM proje_ekip
WHERE proje_id=11)
the second one , is just like the query you wrote above.