SELECT COUNT('2018-02-12')
as ids FROM tg_partner_data
WHERE assign_to = '2'
AND
followup_date = '2018-02-12' AND active='Y'
LIMIT (SELECT count FROM tg_master_count WHERE count_for = 'followup')
I tried to get count as output but this query doesnot works . I am using like this because the limit setting is dynamic.
An immediate problem with your use of LIMIT is that you have no ORDER BY clause. Which first records do you expect from the result set? This is not clear. I will give a generic pattern which you can use to have a subquery limit the number of records.
Consider a simple table with just one column:
col
1
2
3
4
5
Now let's say that you want to limit the number of records in the result set, based on an ordering of col, using some subquery. We can write the following:
SET #rn=0;
SELECT col
FROM
(
SELECT
col,
#rn:=#rn+1 rn
FROM yourTable
ORDER BY
col
) t
WHERE t.rn <= (SELECT 3 FROM dual); -- replace with your own subquery
Demo
The basic idea here is that we simulate row number in a subquery, that is, we assign a row number to each record, ordered according the the col column. Then we subquery that table, and retain only records matching the subquery you want to use to limit.
Related
I've a set of tables and I want to select a random row from within a random one of the tables.
If there's 5 tables
Table1
Table2
Table3
Table4
Table5
Each has the same data format.
I've tried the below, the first part in selecting a random table works but grabbing the info from the table is returning 0 rows.
SELECT * FROM (SELECT `cat_table_name` from `category-defines` GROUP BY `cat_table_name` LIMIT 1) AS x ORDER BY RAND() LIMIT 3
Not every task can be done in a single SQL query.
In SQL, all table names (really, all identifiers) must be fixed at the time the query is parsed. You can't write an SQL query that makes choices of tables (or columns, etc.) based on expressions evaluated during the query.
By analogy: it would be like in any other code, trying to call a function whose name is based on the return value of the function you want to call.
So you can't do what you want in one query.
You could pick the random table name in one query, then use that result as you form the next query.
SELECT `cat_table_name` from `category-defines` GROUP BY `cat_table_name` LIMIT 1
SELECT * FROM `$result_from_previous_query` ORDER BY RAND() LIMIT 3
That's the simplest solution.
Be sure to delimit your table name in back-ticks, just in case one of the table names is FROM or some other reserved keyword.
(Note: the first query above doesn't pick a random table name, it always picks the first table).
A comment above suggests a UNION of all the tables. This is what that would look like:
SELECT *
FROM
(SELECT FLOOR(RAND()*5)+1 AS table_num) AS r
JOIN (
(SELECT 1 AS table_num, * FROM my_table1 ORDER BY RAND() LIMIT 3)
UNION
(SELECT 2 AS table_num, * FROM my_table2 ORDER BY RAND() LIMIT 3)
UNION
(SELECT 3 AS table_num, * FROM my_table3 ORDER BY RAND() LIMIT 3)
UNION
(SELECT 4 AS table_num, * FROM my_table4 ORDER BY RAND() LIMIT 3)
UNION
(SELECT 5 AS table_num, * FROM my_table5 ORDER BY RAND() LIMIT 3)
) AS x USING (table_num)
But this has at least two problems:
It bears the performance cost of picking random rows from every table, just to throw away most of them. Wasteful.
You still have to know the table names in advance, so if they aren't fixed, you end up running another query before this one to get the list of table names.
That is because the main query will be executed on the result of the derived table (in this case the table name), not the actual table name.
As far as my MySQL knowledge stretches you have to split this into two queries, where the first query retrieves the table name and the second query uses the result from the first query. In PHP it would look something like this
//get a random table name
$stmt = $this->pdo->prepare('SELECT `cat_table_name` as table from `category-defines` GROUP BY `cat_table_name` LIMIT 1');
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//select 3 random rows with the table name
$stmt = $this->pdo->prepare('SELECT * FROM '.$row['table'].' ORDER BY RAND() LIMIT 3');
$stmt->execute();
$randomRows = $stmt->fetchAll(PDO::FETCH_ASSOC); //the three random rows
Can anyone please help to get last record from the group.enter image description here
I think you need this:
select * from t where col = 85 order by id desc limit 1
According to your comment, this should get last records for every group: (this assumes that id is unique and "last record" means record, with highest id)
select t.* from t
inner join (select max(id) as maxid from t group by col) s
on t.id = s.maxid
To fetch the 1 row from mysql use 'limit' keyword.
MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses ROWNUM.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
E.g.:
From your screenshot, subscription id is same for multiple id's you want to get last record which id is greater. The below query gets your result, grouped by subscription_id and ordered by id desc and limiting to 1 makes fetching only 1 row from database.
select * from tableName group by subscription_id order by id desc limit 1
You can used last() function.
SELECT LAST(CustomerName) AS LastCustomer FROM Customers;
I have a table with many integers in column named 'data'
data | param
123 1
432 1
123 1
423 2
234 1
423 2
I have a query
SELECT data FROM data_table WHERE param=*something* GROUP BY data
ORDER BY rand() LIMIT 1
That returns a random distinct integer from the table. But I also need to get the total number of integers that I was choosing from. I tried:
SELECT DISTINCT(data) AS data, COUNT(DISTINCT(data)) as count FROM
data_table WHERE param=*something* ORDER BY rand() LIMIT 1
This returns correct number from which data was chosen, but the data returned is no random - it is always the same row. So I need to get number of rows that rand() were selected after WHERE was applied. So making a query on above table should return:
query WHERE param='1':
data count
123 3
query WHERE param='1':
data count
432 3
query WHERE param='1':
data count
234 3
query WHERE param='2':
data count
423 1
This works. I normally don't recommend putting a query in the selector because it evaluates for each row returned. However in this case you are only returning one row so it is OK.
select
count(distinct data) as cnt,
(SELECT data FROM data_table GROUP BY data
WHERE param='xxx'
ORDER BY rand() LIMIT 1) as random
from data_table
WHERE param='xxx'
See this SQL Fiddle to see it work without the where statements.
I think this situation needs to be split in two steps:
Select the random entry where param has the value you want
Count the entries of the data
I propose this solution
set #yourParam = 1; -- Put here the parameter value you want to filter
select
data,
(select count(distinct date) from data_table where param=#yourParam) as `count`
from
data_table
where
param = #yourParam
order by
rand()
limit 1;
Hope this helps you
try this
select
data, (select count(distinct data) from data_table where param=1) as `count`
from
data_table where param = 1
order by rand()
limit 1
DEMO HERE
I think the easiest is to join another select statement to get the total number of rows and add that to your main SELECT statement.
SELECT data AS data, count.count
FROM data
JOIN (SELECT COUNT(DISTINCT(data)) AS count FROM data WHERE parameter = "test") AS count
WHERE parameter = "test"
ORDER BY rand()
LIMIT 1;
Here's a SQL Fiddle
This code can be used to select the first ten records from a table in mysql. How can I do the same to display last ten records from a table which has 1000 records. I want to display the name in asc order dont want to change that.
SELECT name, cost FROM test orderby name asc LIMIT 10 ;
SELECT q.name, q.cost
FROM (SELECT name, cost
FROM test
ORDER BY name DESC LIMIT 10) q
ORDER BY q.name ASC;
The LIMIT clause can take two parameters, which will provide an offset:
The LIMIT clause can be used to constrain the number of rows returned
by the SELECT statement. LIMIT takes one or two numeric arguments,
which must both be nonnegative integer constants (except when using
prepared statements).
With two arguments, the first argument specifies the offset of the
first row to return, and the second specifies the maximum number of
rows to return. The offset of the initial row is 0 (not 1):
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15 To retrieve all
rows from a certain offset up to the end of the result set, you can
use some large number for the second parameter. This statement
retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615; With one argument,
the value specifies the number of rows to return from the beginning of
the result set:
SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows
http://dev.mysql.com/doc/refman/5.0/en/select.html
So with this:
SELECT name, cost FROM test orderby name asc LIMIT 990, 10;
SELECT name, cost
FROM (SELECT name, cost FROM test orderby name desc LIMIT 10) as test
ORDER BY name asc;
You can use ROW_NUMBER() clause for this, this will be helpful for you
select top "N" * from (select ROW_NUMBER() OVER(Order by Col_Name desc) as RowNo,* from Table_Name) Table_Name
Can someone please tell me how to use the group by clause, grouping by one of the keys in the table but yet having the newest timestamp at the top? I have multiple rows of data but I only want to show the newest row
If you want only the most recent one per group:
SELECT somefield
FROM table t1
WHERE timestamp = (SELECT MAX(timestamp)
FROM table t2
WHERE t1.somefield = t2.somefield);
Or just the latest most recent one:
SELECT somefield
FROM table
GROUP BY somefield
ORDER BY MAX(timestamp) DESC
LIMIT 1;
I think you're looking for the ORDER BY clause.
SELECT Foo.Bar, Foo.SomeTimestamp
FROM Foo
ORDER BY Foo.SomeTimestamp DESC
If you're grouping by a column, you're probably returning aggregate data. If the timestamp is unique for each row of aggregate data, you may need to use the MAX function (or the like) to return a single timestamp for each group. For example:
SELECT Foo.TypeID, SUM(Foo.Price) AS Price, MAX(Foo.OrderDate) AS LastOrder
FROM Foo
GROUP BY Foo.TypeID
ORDER BY MAX(Foo.OrderDate) DESC
If you only want the first row, you can use the LIMIT clause:
SELECT Foo.Bar, Foo.SomeTimestamp
FROM Foo
ORDER BY Foo.SomeTimestamp DESC
LIMIT 0, 1
This starts at row 0 and returns at most 1 row.