Let's consider a made up example
SELECT id, name, score.score FROM
someTable,
(select someTableId, count(*) as score FROM SecondTable GROUP BY someTableId) as score
WHERE score.someTableId == id
ORDER BY score.score DESC
Let's now assume that I have a backend computing my scoring, and that I would like to remove the subquery and insert my own data instead. I would like to know how to do this.
I would like to do something like (this is the question, because what's below doesn't work):
SELECT id, name, score.score FROM
someTable,
((12,324), (1, 342)) as score(id, score)
WHERE score.someTableId == id
ORDER BY score.score DESC
Here is an example of external data substitution to a subquery:
SELECT * FROM users WHERE id IN (SELECT user_id FROM posts WHERE thread_id = 12 GROUP BY user_id);
Without a subquery and with external data:
SELECT * FROM users WHERE id IN (1,2,3);
If I understood you correctly :
SELECT id, name, score.score FROM
someTable,
(SELECT 12 as someTableId,324 as score UNION ALL SELECT 1, 342 <UNION ALL....>) as score(id, score)
WHERE score.someTableId == id
ORDER BY score.score DESC
Thats the only way you can do it, it doesn't actually replace the the subquery, but it replace the select from the table and can improve performance if thats what you are looking for.
In MySQL you don't need to specify a from clause like a dummy table when you are just looking to fetch dummy data.
Other DBMS require a dummy table name (typically DUAL) but in MySQL it's rather straightforward:
SELECT 12 AS id, 324 AS score
UNION ALL SELECT 2, 65
UNION ALL SELECT 3, 598
UNION ALL SELECT 4, 244
You can use this as any other result-set.
Related
I am using MySQL 8.0
My table looks like this:
group user_id score
A 1 33
B 2 22
A 3 22
B 4 22
I want it to return
group user_id score
A 1 33
B 2 22
note that even though group B has same score user_id=2 is final winner since he/she has lower user_id
How to improve from below query...?
SELECT group, user_id, max(score)
from table
Thanks in advance!
#Ambleu you are on the right track using MAX(), but to do this you need to use it in addition to MIN(), and also use a sub query to get the MAX(score) like this:
SELECT `mt`.`group`,
MIN(`mt`.`user_id`) AS `user_id`,
`mt`.`score`
FROM `myTable` AS `mt`
JOIN (SELECT `group`,
MAX(`score`) AS `score`
FROM `myTable`
GROUP BY `group`) AS `der` ON `der`.`group` = `mt`.`group`
AND `der`.`score` = `mt`.`score`
GROUP BY `mt`.`group`, `mt`.`score`
Here are your tables and the solution query mocked up on db-fiddle.
If this doesn't get you what you need please let me know and I'll try to assist further.
In MySQL 8.0, I would recommend window functions:
select grp, user_id, score
fom (
select t.*,
row_number() over(partition by grp order by score desc, user_id) rn
from mytable t
) t
where rn = 1
Alternatively, you can use a correlated subquery for filtering:
select t.*
from mytable t
where user_id = (
select t1.user_id
from mytable t1
where t1.grp = t.grp
order by t1.score desc, t1.user_id limit 1
)
The second query would take advantage of an index on (grp, score desc, user_id).
Side note: group is a language keyword, hence a poor choice for a column name. I renamed it to grp in the queries.
Lets say I have two subqueries in a UNION statement like so:
(
SELECT *
FROM users
ORDER BY registration_date
)
UNION ALL
(
SELECT *
FROM food
ORDER BY popularity
)
The output is the following:
Bob
Alice
Steve
Mark
...
Sandwich
Pizza
Burger
Fries
...
Is it possible to output them in an alternating fashion, such that the output is:
Bob
Sandwich
Alice
Pizza
Steve
Burger
Mark
Fries
...
Each query output is thousands of items.
You could use row_number() if you are running MySQL 8.0:
(select name, 1 src, row_number() over(order by registration_date) rn from users)
union all
(select name, 2, row_number() over(order by popularity) from food)
order by rn, src
In each unioned subquery, we use row_number() to rank the records, and add another column, called src to identify from which table the record comes from.
Then all that is left to do is order by the assigned row_number(), using the additional column to alternate the records.
Note that I modified your query to enumerate the columns being selected in the subqueries; select * is generally not a good practice, especially with union all, which requires both datasets to have the same number of columns (with equivalent datatypes).
Just in case you are not using MySQL 8+, you can still simulate ROW_NUMBER using a correlated count query:
(
SELECT 1 AS idx, name,
(SELECT COUNT(*) FROM users u2 WHERE u2.registration_date < u1.registration_date) rn
FROM users u1
)
UNION ALL
(
SELECT 2, name,
(SELECT COUNT(*) FROM food f2 WHERE f2.popularity < f1.popularity) rn
FROM food f1
)
ORDER BY
rn,
idx;
DECLARE #id INT;
SET #id :=0;
SELECT id,t.* FROM(
SELECT u.*,(#id:=#id+1) AS id
FROM users u
ORDER BY registration_date
)
UNION ALL
(
SELECT f.*,(#id:=#id+2) AS id
FROM food f
ORDER BY popularity
)t
ORDER BY id;
I have basic table looking like:
When I am using the Query:
SELECT *, SUM(cr) AS cr, SUM(dr) AS dr FROM my_table GROUP BY id
I am getting:
and that's correct!
What's the proper query to get (each sum in different row):
I already tried GROUP BY ID,CR,DR and GROUP BY CR,DR,ID but with not the results that I wanted. (I don't care if the 0 values are also NULL)
You can do:
select id, sum(dr) as dr, 0 as cr from my_table group by id
union all
select id, 0, sum(cr) from my_table group by id
order by id, dr desc
I have two queries one will return data ordered by likes and in the user city the other one return data by the distance .
so if query 1 return : id 1,2,3 (order by likes)
and query 2 return : id 4,5,6 (order by distance)
i need the final set results to be 1,2,3,4,5,6
i've tried to do union between the two queries but it's not working. any other suggestions ?
You can use left join or union according to this link.
Union ALL also works like you can see here.
Example: SELECT 1 UNION ALL SELECT 2
the solution was to put a limit to each query then the union will work correct :
(SELECT DISTINCT ID, 'a' as type,... FROM table1 GROUP BY ID ORDER BY likesDESC limit 50) union all( SELECT DISTINCT ID, 'b' as type,....FROM table1 GROUP BY ID ORDER BY distance limit 50) order by type asc.
I'm trying to create a search function in different tables using UNION and what happened is that the id's are duplicating making the search go wrong. How can I merge different tables into one while no id's are in common?
Here is the example
table1
id name desc
1 henry post
2 albert doth
3 jun cloth
table2
id name desc
1 kin revenge
2 pot eve
The result SHOULD be like this
id name desc
1 henry post
2 albert doth
3 jun cloth
4 kin revenge
5 pot eve
Please help me. Thanks.
In most databases, you would add a new id using the ANSI standard row_number() function:
select row_number() over (order by which, id) as newid, name, description
from (select 1 as which, t1.* from table1 t1 union all
select 2 as which, t2.* from table2 t2
) t;
Note that desc is a really bad name for a column, because it is a SQL keyword and usually a reserved word.
EDIT:
MySQL doesn't support this ANSI standard functionality. Instead, use variables:
select (#rn := #rn + 1) as newid, name, description
from (select 1 as which, t1.* from table1 t1 union all
select 2 as which, t2.* from table2 t2
) t cross join
(select #rn := 0) vars
order by which, id;
I've include the order by so the rows remain in the same order that you seem to want them in -- rows from the first table followed by rows from the second table. If you don't care about the order, just drop the order by.
For SQLite, the calculation is much more painful:
with cte as (
select 1 as which, t1.* from table1 t1 union all
select 2 as which, t2.* from table2 t2
)
select (select count(*)
from cte cte2
where cte2.which < cte.which or (ct2.which = cte.which and cte2.id <= cte.id
) as id,
name, description
from cte;
In MySql, you can simulate the row_number() function of Sql Server and Oracle using a mutating variable hack:
set #rownum := 0;
SELECT #rownum:=#rownum+1 AS` row_number`, `name`, `desc`
FROM
(
SELECT `name`, `desc` FROM table1
UNION
SELECT `name`, `desc` FROM table2
) AS x;
SqlFiddle
It looks like you have to Generate Id's so you can make you Union query as Sub select and generate Id's in Outer Query
MySQL does not have any system function like SQL Server’s row_number () to generate the row number for each row. However, it can be generated using the variable in the SELECT statement
SET #row_number:=0;
SELECT #row_number:=#row_number+1 As Id,
NAME,
desc
FROM (SELECT NAME,desc
FROM table1
UNION ALL
SELECT NAME,desc
FROM table2
UNION ALL
........
........) A
Order by NAME -- Change the column in Order by in which order you want to create New ID's