Retrieving data from SQL table - php

I have a table in which all action logs are stored. It contains "user_id" (to mark user), "statement_id" (to mark statement that has been worked on), "action_date" (to mark action time) and "action_type" (to mark what action was done). A user can work on many statements on which many actions can be performed.
I need to produce a query that will show what statements were worked on at a specific time (let's say from March 1, 2018 to March 30, 2018) - that I can do. The difficulty for me is to limit the outcome. I mean precisely how to limit the outcome from this:
Statements that were worked on: 30, 30, 30, 18, 18, 42, 42, 42
To this:
Statements that were worked on: 30, 18, 42
I tried to work with queries like this one but I'm no professional. I find it difficult to understand the concept of some limiting SQL commands.
SELECT * FROM action_log
WHERE user_id = 1
AND action_date >= 1519858800
AND action_date <= 1522447200
GROUP BY user_id
HAVING user_id = 1
ORDER BY id DESC
I would be very grateful for any help.

I think you are looking for SELECT DISTINCT:
SELECT DISTINCT statement_id
FROM action_log al
WHERE user_id = 1 AND
action_date >= 1519858800 AND action_date <= 1522447200
ORDER BY statement_id DESC;
You might find this easier to maintain by using UNIX_TIMESTAMP():
SELECT DISTINCT statement_id
FROM action_log al
WHERE user_id = 1 AND
action_date >= UNIX_TIMESTAMP('2018-03-01') AND
action_date <= UNIX_TIMESTAMP('2018-03-30')
ORDER BY statement_id DESC;

I guess you only need unique values.
In SQL there is a special statement for this.
Use SELECT DISTINCT
SELECT DISTINCT * FROM action_log WHERE user_id = 1 AND action_date >= 1519858800 AND action_date <= 1522447200 GROUP BY user_id HAVING user_id = 1 ORDER BY id DESC;

You can use between for comparing action_date. And you can eliminate having condition because that is already used in where. WHERE user_id = 1 and HAVING user_id = 1 will result you the same. Hope following code will work for you.
SELECT * FROM action_log WHERE user_id = 1 AND action_date between '1519858800' AND '1522447200' GROUP BY statement_id ORDER BY id DESC

Related

PHP MYSQL General Error returned when using LIMIT [duplicate]

This question already has answers here:
Implement paging (skip / take) functionality with this query
(6 answers)
Closed 1 year ago.
I have this query with MySQL:
select * from table1 LIMIT 10,20
How can I do this with SQL Server?
Starting SQL SERVER 2005, you can do this...
USE AdventureWorks;
GO
WITH OrderedOrders AS
(
SELECT SalesOrderID, OrderDate,
ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'
FROM Sales.SalesOrderHeader
)
SELECT *
FROM OrderedOrders
WHERE RowNumber BETWEEN 10 AND 20;
or something like this for 2000 and below versions...
SELECT TOP 10 * FROM (SELECT TOP 20 FROM Table ORDER BY Id) ORDER BY Id DESC
Starting with SQL SERVER 2012, you can use the OFFSET FETCH Clause:
USE AdventureWorks;
GO
SELECT SalesOrderID, OrderDate
FROM Sales.SalesOrderHeader
ORDER BY SalesOrderID
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY;
GO
http://msdn.microsoft.com/en-us/library/ms188385(v=sql.110).aspx
This may not work correctly when the order by is not unique.
If the query is modified to ORDER BY OrderDate, the result set returned is not as expected.
This is how I limit the results in MS SQL Server 2012:
SELECT *
FROM table1
ORDER BY columnName
OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY
NOTE: OFFSET can only be used with or in tandem to ORDER BY.
To explain the code line OFFSET xx ROWS FETCH NEXT yy ROW ONLY
The xx is the record/row number you want to start pulling from in the table, i.e: If there are 40 records in table 1, the code above will start pulling from row 10.
The yy is the number of records/rows you want to pull from the table.
To build on the previous example: If table 1 has 40 records and you began pulling from row 10 and grab the NEXT set of 10 (yy).
That would mean, the code above will pull the records from table 1 starting at row 10 and ending at 20. Thus pulling rows 10 - 20.
Check out the link for more info on OFFSET
This is almost a duplicate of a question I asked in October:
Emulate MySQL LIMIT clause in Microsoft SQL Server 2000
If you're using Microsoft SQL Server 2000, there is no good solution. Most people have to resort to capturing the result of the query in a temporary table with a IDENTITY primary key. Then query against the primary key column using a BETWEEN condition.
If you're using Microsoft SQL Server 2005 or later, you have a ROW_NUMBER() function, so you can get the same result but avoid the temporary table.
SELECT t1.*
FROM (
SELECT ROW_NUMBER OVER(ORDER BY id) AS row, t1.*
FROM ( ...original SQL query... ) t1
) t2
WHERE t2.row BETWEEN #offset+1 AND #offset+#count;
You can also write this as a common table expression as shown in #Leon Tayson's answer.
SELECT *
FROM (
SELECT TOP 20
t.*, ROW_NUMBER() OVER (ORDER BY field1) AS rn
FROM table1 t
ORDER BY
field1
) t
WHERE rn > 10
Syntactically MySQL LIMIT query is something like this:
SELECT * FROM table LIMIT OFFSET, ROW_COUNT
This can be translated into Microsoft SQL Server like
SELECT * FROM
(
SELECT TOP #{OFFSET+ROW_COUNT} *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rnum
FROM table
) a
WHERE rnum > OFFSET
Now your query select * from table1 LIMIT 10,20 will be like this:
SELECT * FROM
(
SELECT TOP 30 *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rnum
FROM table1
) a
WHERE rnum > 10
SELECT TOP 10 * FROM table;
Is the same as
SELECT * FROM table LIMIT 0,10;
Here's an article about implementing Limit in MsSQL Its a nice read, specially the comments.
This is one of the reasons I try to avoid using MS Server... but anyway. Sometimes you just don't have an option (yei! and I have to use an outdated version!!).
My suggestion is to create a virtual table:
From:
SELECT * FROM table
To:
CREATE VIEW v_table AS
SELECT ROW_NUMBER() OVER (ORDER BY table_key) AS row,* FROM table
Then just query:
SELECT * FROM v_table WHERE row BETWEEN 10 AND 20
If fields are added, or removed, "row" is updated automatically.
The main problem with this option is that ORDER BY is fixed. So if you want a different order, you would have to create another view.
UPDATE
There is another problem with this approach: if you try to filter your data, it won't work as expected. For example, if you do:
SELECT * FROM v_table WHERE field = 'test' AND row BETWEEN 10 AND 20
WHERE becomes limited to those data which are in the rows between 10 and 20 (instead of searching the whole dataset and limiting the output).
In SQL there's no LIMIT keyword exists. If you only need a limited number of rows you should use a TOP keyword which is similar to a LIMIT.
Must try. In below query, you can see group by, order by, Skip rows, and limit rows.
select emp_no , sum(salary_amount) from emp_salary
Group by emp_no
ORDER BY emp_no
OFFSET 5 ROWS -- Skip first 5
FETCH NEXT 10 ROWS ONLY; -- limit to retrieve next 10 row after skiping rows
Easy way
MYSQL:
SELECT 'filds' FROM 'table' WHERE 'where' LIMIT 'offset','per_page'
MSSQL:
SELECT 'filds' FROM 'table' WHERE 'where' ORDER BY 'any' OFFSET 'offset'
ROWS FETCH NEXT 'per_page' ROWS ONLY
ORDER BY is mandatory
This is a multi step approach that will work in SQL2000.
-- Create a temp table to hold the data
CREATE TABLE #foo(rowID int identity(1, 1), myOtherColumns)
INSERT INTO #foo (myColumns) SELECT myData order By MyCriteria
Select * FROM #foo where rowID > 10
SELECT
*
FROM
(
SELECT
top 20 -- ($a) number of records to show
*
FROM
(
SELECT
top 29 -- ($b) last record position
*
FROM
table -- replace this for table name (i.e. "Customer")
ORDER BY
2 ASC
) AS tbl1
ORDER BY
2 DESC
) AS tbl2
ORDER BY
2 ASC;
-- Examples:
-- Show 5 records from position 5:
-- $a = 5;
-- $b = (5 + 5) - 1
-- $b = 9;
-- Show 10 records from position 4:
-- $a = 10;
-- $b = (10 + 4) - 1
-- $b = 13;
-- To calculate $b:
-- $b = ($a + position) - 1
-- For the present exercise we need to:
-- Show 20 records from position 10:
-- $a = 20;
-- $b = (20 + 10) - 1
-- $b = 29;
If your ID is unique identifier type or your id in table is not sorted you must do like this below.
select * from
(select ROW_NUMBER() OVER (ORDER BY (select 0)) AS RowNumber,* from table1) a
where a.RowNumber between 2 and 5
The code will be
select * from limit 2,5
better use this in MSSQLExpress 2017.
SELECT * FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) as [Count], * FROM table1
) as a
WHERE [Count] BETWEEN 10 and 20;
--Giving a Column [Count] and assigning every row a unique counting without ordering something then re select again where you can provide your limits.. :)
One of the possible way to get result as below , hope this will help.
declare #start int
declare #end int
SET #start = '5000'; -- 0 , 5000 ,
SET #end = '10000'; -- 5001, 10001
SELECT * FROM (
SELECT TABLE_NAME,TABLE_TYPE, ROW_NUMBER() OVER (ORDER BY TABLE_NAME) as row FROM information_schema.tables
) a WHERE a.row > #start and a.row <= #end
If i remember correctly (it's been a while since i dabbed with SQL Server) you may be able to use something like this: (2005 and up)
SELECT
*
,ROW_NUMBER() OVER(ORDER BY SomeFields) AS [RowNum]
FROM SomeTable
WHERE RowNum BETWEEN 10 AND 20

Does Last 3 rows have the same user id?

I'm looking to see if the last 3 rows have the same userId...
I've tried count, select distinct with no luck. Any ideas?
id userId gameId switchId won
--------------------------------
1 1515 5 475 0
2 1515 5 475 0
3 1515 5 475 0
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$st = $db->prepare("SELECT COUNT(userId) AS total FROM arcadeGamesInPlay WHERE userId=:userid,gameId=:gameId AND switchId=:switchId AND won=:won ORDER by id DESC LIMIT :limit"); // need to filter for next auction
$st->bindParam(':userId', $userId);
$st->bindParam(':gameId', $gameId);
$st->bindParam(':switchId', $switchId);
$st->bindParam(':won', $won);
$st->bindParam(':limit', $limit);
$limit=3;
$won=0;
$st->execute();
$r = $st->fetch(PDO::FETCH_ASSOC);
$playedLastThreeGames= $r['total'];
You need a nested query for this. Imagine a query like this:
SELECT COUNT(DISTINCT userId) FROM arcadeGamesInPlay WHERE id IN (1, 2, 3);
This will return the number of unique userids that were found in the three rows listed - if it returns 1, then you know they're all the same.
You can combine that with a query to select the last three rows. Perhaps something like this:
SELECT id FROM arcadeGamesInPlay ORDER BY id DESC LIMIT 3
...although you may want to add a WHERE clause as well.
Altogether, your query would look like this:
SELECT COUNT(DISTINCT userId)
FROM arcadeGamesInPlay
WHERE id IN (
SELECT id
FROM arcadeGamesInPlay
ORDER BY id DESC
LIMIT 3
);
All that being said, you haven't specified what database you're actually connecting to - and if it's MySQL, you're going to run into problems, because MySQL doesn't support a LIMIT clause on a subquery with the IN operator.
An alternative form of the subquery that will work with MySQL looks like this:
SELECT COUNT(DISTINCT userId)
FROM (
SELECT userId
FROM arcadeGamesInPlay
ORDER BY id DESC
LIMIT 3
) u;
An SQL Fiddle that shows both queries can be seen here: http://sqlfiddle.com/#!2/dda29/4
I've commented out the LIMIT part of the first query so it will work in MySQL. If you change the database engine to something else (PostgreSQL for example), you should be able to uncomment that and have both queries work properly.

Select on Mysql inverse order

i have a MySql table that consists of 2 basic things:
The id and a value.
To show that on my page, i need to select, for example, the last 100 rows on reversed order.
So imagine that someone is putting data on it:
Id, value
1, 10
2, 9
3, 21
4, 15
i need, to select the last "3" rows (LIMIT + ORDER Clause), but not like this: 4,3,2 but like this: 2,3,4.
I know how to do that on code, but maybe there is a simple solution for that on Mysql and i don`t know.
Thanks
My SQL Query is like this right now:
SELECT `Data`.`id`, `Data`.`log_id`, `Data`.`value`, `Data`.`created` FROM `control_panel`.`datas` AS `Data` WHERE `Data`.`id` > 1000 AND `Data`.`log_id` = (2) ORDER BY `Data`.`id` DESC LIMIT 100
You need to wrap the first ORDER BY in a subselect which will return a limited selection ordered in descending order, then you can order that result in the outer query in ascending order:
SELECT
a.*
FROM
(
SELECT id, value
FROM tbl
ORDER BY id DESC
LIMIT 3
) a
ORDER BY
a.id
One way to do this would be with a sub-select.
SELECT *
FROM (SELECT * FROM table_name ORDER BY id DESC LIMIT 3) tmp
ORDER BY id ASC
simply
SELECT t.*
(SELECT * FROM table_name
ORDER BY column_name DESC
LIMIT 0,3) t
ORDER BY t.column_name ASC
use DESC to descending order, ASC to increasing order

Ordering the SQL query in a particular order

Say i have a table Guest and it has column g_id : values 1 to 10.
Now i want the query to return me the g_id's neither in ascending order nor in descending..
but i want the 4th then 3rd and then 5th entry, in this particular order.
Also i want just the 4th 3rd and 5th entry.
say my entries have an id and a name . ;i.e. my table Guest has these two tables.
Now my table is as following.
1 A
2 B
3 C
4 D
5 E
6 F
7 G
8 H
9 I
10 J
Now i want just the entry with 4th 3rd and 5th g_id, and in this particular order.
How do i write the SQL query?
Thanks.
Select * from Guest ___________???
Kindly fill in the gaps.
You can use a CASE statement in your ORDER BY to use a fake column to sort on and a WHERE IN clause to only return the values you need.
SELECT *
FROM Guest
WHERE g_id IN (3, 4, 5)
ORDER BY
CASE WHEN g_id = 4 THEN 1
WHEN g_id = 3 THEN 2
WHEN g_id = 5 THEN 3
END
What is the order that deteremines whether something is 4th, 3rd or 5th? Without an ORDER BY clause, the data is returned in an indeterminate order by SQL. You cannot rely on the order that rows are entered or stored in the database table itself.
You can hard-code what you are asking like this:
select *
from Guest
order by case
when g_id = 4 then 1
when g_id = 3 then 2
when g_id = 5 then 3
else 4
end
One solution is the case statement:
select g_id from (
select g_id, case g_id
when 4 then 1
when 3 then 2
when 5 then 3
else 0
end virtcol
where virtcol != 0
order by virtcol
);
I'm not sure how set your ordering will be, but you can order by specifics:
ORDER BY
g_id = 4 DESC,
g_id = 3 DESC,
g_id = 5 DESC
You may be better off selecting the entries as they are and doing something like this in your php code:
$order = array('4 ', '3 ', '5 ');
$data = array();
while ($row = $result->fetch()) {
$data["$row->g_id "] = $row;
}
$data = array_merge(array_flip($order), $data);
I think that the answer mostly depends on the DBMS you are working on.
In Oracle the query below, even though inefficient, should work
select * from
(select * , rownum as order from guest order by id asc ) b
where b.order = 4
UNION
select * from
(select * , rownum as order from guest order by id asc ) b
where b.order = 3
UNION
select * from
(select * , rownum as order from guest order by id asc ) b
where b.order = 5
Not sure if something of more efficient is possible with a simple query,
i would use the monster above only and only if the table you are querying is very small.
You also have another option if the table is big and you have to extract only the first rows. In the case you described, I would retrieve the first 5 rows and then programmatically I would extract the rows in position 4,3,5.
you can extract the first 5 rows with this query in oracle
select * from guest order by id asc where rownum < 6
This query will get you the 3rd, 5th, and 4th items (limit 2, 1 means "retrieve starting with 3rd item, with total number retrieved = 1 records)
(select g_id from Guest limit 2,1)
UNION (select g_id from Guest limit 4,1
UNION (select g_id from Guest limit 3,1)

PHP: SELECT ing 2 tables?

I have a activities page and a statusmessages page for each user.
In activities it contains what the users have done, such as being friends with someone, commented on pictures and so.
users_activities
id | uID | msg | date
In users_statusmessages, I got the statusmessages, the user creates.
users_statuses
id | uID | message | date
uID is the user´s id.
Now i would like to select both of them and while{} them in one. Where they get sorted by date desc ( as the date in both tables is UNIX timestamp).
So something like WHERE uID = '$userID' ORDER BY date DESC
So example of how i wish it to look:
User: Today is a good day (message) (date: 1284915827) (users_statuses)
User have added as Jack as friend (msg) (date: 1284915811) (users_activities)
User: I have a hard day today (message) (date: 1284915801) (users_statuses)
User have commented on Jacks picture (msg) (date: 1284915776) (users_activities)
How should i do this the right way?
You need to use the UNION operator:
SELECT ua.msg,
ua.date,
'activity' AS is_table
FROM USERS_ACTIVITIES ua
WHERE ua.uid = '{$userID}'
UNION ALL
SELECT us.message,
us.date,
'status'
FROM USERS_STATUSES us
WHERE us.uid = '{$userID}'
ORDER BY `date`
UNION
UNION removes duplicates. UNION ALL does not remove duplicates, and is faster for it.
But the data types at each position in the SELECT must match. In the query provided, you can see that the date column is referenced in the second position. You'd get an error if the column order were reversed between the first and second query.
The ORDER BY is applied to the result of the UNION'd query in standard SQL. In MySQL, that includes the LIMIT clause. But MySQL also supports putting brackets around the UNION'd queries so you can use ORDER BY & LIMIT before the queries are UNION'd.
You're going to want to use a union
http://dev.mysql.com/doc/refman/5.0/en/union.html
This is untested...
(SELECT uID, msg as message, date from users_activities)
UNION
(SELECT uId, message, date from users_statuses) order by date desc limit 20
There are a lot more examples on that page
Something like this would do
SELECT act.*,status.* FROM users_activities act, users_statuses status WHERE act.id = status.id AND status.id = '$UID' ORDER BY status.date,act.date DESC LIMIT 30
Spaced out for visual purposes:
SELECT
act.*,status.*
FROM
users_activities act,
users_statuses status
WHERE
act.id = status.id
AND
status.id = '$UID'
ORDER BY
status.date,act.date DESC
LIMIT
30

Categories