MySQL WHERE clause usage - mysql

MySQL
I was trying to get values of category_id in between 9 to Maximum category id (use sub-query), without using Max function.
I tried the MySQL query given below. It works for the latter part, i.e. it gives category_id uptil maximum category_id. But, it gives all category ids from the very beginning (1), i.e. it does not start from '9'.
SELECT columns
FROM table_name
WHERE (9 <= category_id <= (
SELECT category_id
FROM table_name
ORDER BY category_id
DESC LIMIT 1 )
);

Logically your query is
SELECT { columns }
FROM table_name
WHERE 9 <= category_id;
Your condition which uses subquery makes no sense - column value cannot be greater than maximal value in this column.

Related

Is there a query to select random row from a set of returned rows from a SELECT statement in sql?

Suppose a SELECT query returns 10 rows. Is there any one line query such as this (which I tried but did not work) to select one random row from return results of a SELECT query -
select name from (select * from my_table where age > 10 ORDER BY age ASC AS rows)
ORDER BY RAND() LIMIT 1;
One approach is to do LIMIT RAND() and enclose this in another SELECT statement which does LIMIT 1.
Another approach is to add a new column to the table, initialize it with RAND(), and then select from it, ordering by the random column with LIMIT 1. You may even be able to do this on the fly, by JOINing your original table with another table consisting of a single column that takes values from RAND().
Your logic is correct, you just have the syntax wrong.
select name from (
select *
FROM my_table
where age > 10) AS rows
ORDER BY RAND()
LIMIT 1;
You were missing FROM in the subquery, and the alias for the subquery goes outside the parentheses.
DEMO

Mysql match exact set of result in a single table

I am having trouble with generating result set. This is what my 'user_roles' table looks like,
id user_id role_id
1 1 1
2 1 2
3 2 1
4 3 1
5 3 2
6 3 3
... ... ...
I want this result where user has exact both roles i:e 1 and 2, I do not want those user having roles other than 1,2.
id user_id role_id
1 1 1
2 1 2
... ... ...
I have tried so far,
SELECT
*
FROM
`user_roles`
WHERE `role_id` IN (1,2)
HAVING COUNT(id) = 2
But, it returns null.
Why your query doesn't work
HAVING applies after GROUP BY and your query doesn't have one. When the query contains HAVING or GROUP BY aggregate functions but it doesn't contain the GROUP BY clause, a single group containing all the selected rows is created.
Before applying HAVING, your query selects the rows having id in 1..5 (i.e. 5 rows). A single group is created from them, COUNT(id) returns 5 and the HAVING condition doesn't match. That's why the query doesn't return anything.
In order to correctly count the number of roles of each user it needs to group the records by user_id:
SELECT `user_id`
FROM `user_roles`
WHERE `role_id` IN (1, 2)
GROUP BY `user_id`
HAVING COUNT(`id`) = 2
This way, the WHERE clause selects the user having the roles 1 or 2 (but it ignores other roles), the GROUP BY clause allows the function COUNT(id) to count the number of selected roles for each user and the HAVING clause keeps only those users having both roles (1 and 2). The SELECT clause is not allowed to contain * because for the columns that are not in the GROUP BY clause, MySQL is free to pick any value it finds in the corresponding column and it may return different results on different executions of the query.
However, the query above doesn't return the values you want. It completely ignore the roles that are not 1 or 2 and it will return the user having user_id = 3.
A query that works
This query returns the users having only the roles 1 and 2 is:
SELECT `user_id`
FROM `user_roles`
GROUP BY `user_id`
HAVING COUNT(`role_id`) = 2 AND GROUP_CONCAT(`role_id`) = '1,2'
The condition COUNT(role_id) = 2 is not needed. In theory it should improve the execution speed (because counting works faster that string concatenation) but in real life it might have no impact whatsoever. The MySQL engine knows better.
Update
#martin-schneider asks in a comment:
is the order of GROUP_CONCAT(role_id) deterministic? or could it be that the result is '2,1'?
It's a very good question that has the answer in the documentation of function GROUP_CONCAT():
To sort values in the result, use the ORDER BY clause. To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword.
The complete query is:
SELECT `user_id`
FROM `user_roles`
GROUP BY `user_id`
HAVING COUNT(`role_id`) = 2
AND GROUP_CONCAT(`role_id` ORDER BY `role_id` ASC SEPARATOR ',') = '1,2'
I omitted ORDER BY and SEPARATOR because their default values (sort ascending by the values that are concatenated and use comma as separator) are good for our needs in this query.
Important to notice
There is a limit for the length of the value computed by the GROUP_CONCAT() function. Its result is truncated to the value stored in the system variable group_concat_max_len whose default value is 1024.
This value can be increased using the SET MySQL statement before running the query:
SET group_concat_max_len = 1000000
However, for this particular query the default limit of 1024 characters is more than enough.
You could aggregate by user_id and use HAVING:
SELECT *
FROM `user_roles`
WHERE `user_id` IN (SELECT user_id
FROM `user_roles`
GROUP BY user_id
HAVING SUM(role_id IN (1,2)) = 2
AND SUM(role_id NOT IN (1,2)) = 0);
LiveDemo*
*SQLFiddle does not respond so SQL Server equivalent
Note:
I assumed that user_id, role_id are unique and not null.

MYSQL to order before grouping by

I have the following:
user_id date_created project_id
3 10/10/2013 1
3 09/10/2013 1
5 10/10/2013 1
8 10/10/2013 1
10 10/10/2013 1
3 08/10/2013 1
The end result i want is:
user_id date_created project_id
3 10/10/2013 1
5 10/10/2013 1
8 10/10/2013 1
10 10/10/2013 1
Context:
I have this thing called an influence, and a user can have many influences for a project.
I want to get a list of the latest influence from a user on a project.
I have tried:
select * from influences
where project_id = 1
group by user_id
ORDER BY created_at DESC
but of course this ignores first ordering by user created at, and then ordering the full list. It simply just squishes the users together and orders the end list
THE LARAVEL - Eloquent FOR THE ANSWER PROVIDED IS THIS:
return Influence::select( "user_id", "influence", DB::raw( "MAX(created_at) as created_at" ) )
->where( "project_id", "=", $projectID )
->groupBy( "user_id", "project_id" )->get();
You don't want to order before group by, because given the structure of your query, it won't necessary do what you want.
If you want the most recently created influence, then get it explicitly:
select i.*
from influences i join
(select user_id, max(created_at) as maxca
from influences i
where project_id = 1
group by user_id
) iu
on iu.user_id = i.user_id and iu.maxca = i.created_at
where i.project_id = 1;
Your intention is to use a MySQL extension that the documentation explicitly warns against using. You want to include columns in the select that are not in the group by. As the documentation says:
MySQL extends the use of GROUP BY so that the select list can refer to
nonaggregated columns not named in the GROUP BY clause. This means
that the preceding query is legal in MySQL. You can use this feature
to get better performance by avoiding unnecessary column sorting and
grouping. However, this is useful primarily when all values in each
nonaggregated column not named in the GROUP BY are the same for each
group. The server is free to choose any value from each group, so
unless they are the same, the values chosen are indeterminate.
Furthermore, the selection of values from each group cannot be
influenced by adding an ORDER BY clause. Sorting of the result set
occurs after values have been chosen, and ORDER BY does not affect
which values within each group the server chooses.
Use this:
SELECT user_id, project_id, MAX(date_created) as latest
FROM influences
WHERE project_id = 1
GROUP BY user_id, project_id
How it works: MySQL selects all the rows that match the WHERE conditions and sorts them by user_id then, for each user_id by project_id. From each set of rows having the same user_id and project_id it will produce a single row in the final result set.
You can use in the SELECT clause the columns used in the GROUP BY clause (user_id and project_id); their values are unambiguous: all the rows from each group have the same user_id and project_id.
You can also use aggregate functions. Each of them uses one column from all the rows in the group to compute a single value. The most recent created_at is, of course, MAX(created_at).
If you select a column that is neither included in the GROUP BY clause, nor passed to an aggregate function (like created_at you have in your query), MySQL has no hint how to compute that value. The standard SQL forbids it (the query is not valid) but MySQL allows it. It will simply pick a value from that column but there is no way to make it pick it from a specific row because this is, in fact, undefined behaviour.
You can omit the project_id from the GROUP BY clause because the WHERE clause will make all the rows having the same project_id. This will coincidentally make the result correct even if project_id does not appear in a GROUP BY clause and it's not computed using an aggregate function.
I recommend you to keep project_id into the GROUP BY clause. It doesn't affect the result or the query speed and it allows you to loose the filtering conditions (f.e. use WHERE project_id IN (1, 2)) always get the correct result (this doesn't happen if you remove it from GROUP BY).

How do I get the max id from the first n id's in a MySQL table?

I am trying to get the max id of the first n id's in a MySQL database table where the ids are not necessarily sequential. The first n id's are determined by ordering by id ascending. I am using the following query, but this returns the max id in the entire table.
SELECT MAX( id )
FROM files
ORDER BY id ASC
LIMIT 8750000
What am I doing wrong, or ... how do I do this?
SELECT MAX(t.id) FROM
(SELECT id FROM files order by id ASC limit <n>) AS t ;
Of course you will need to replace <n> with an actual value you need.

Select most common value from a field in MySQL

I have a table with a million rows, how do i select the most common(the value which appears most in the table) value from a field?
You need to group by the interesting column and for each value, select the value itself and the number of rows in which it appears.
Then it's a matter of sorting (to put the most common value first) and limiting the results to only one row.
In query form:
SELECT column, COUNT(*) AS magnitude
FROM table
GROUP BY column
ORDER BY magnitude DESC
LIMIT 1
This thread should shed some light on your issue.
Basically, use COUNT() with a GROUP BY clause:
SELECT foo, COUNT(foo) AS fooCount
FROM table
GROUP BY foo
ORDER BY fooCount DESC
And to get only the first result (most common), add
LIMIT 1
To the end of your query.
In case you don't need to return the frequency of the most common value, you could use:
SELECT foo
FROM table
GROUP BY foo
ORDER BY COUNT(foo) DESC
LIMIT 1
This has the additional benefit of only returning one column and therefore working in subqueries.