how to get last inserted date in php MYSQL - php

I have two tables, and I want to get the last enterd date.
The first table is seeker:
seeker_nic-----username
111-------------ali
222-------------umer
333-------------raza
The second one is requestblood:
id-------seeker_nic-----requireddate
1------- 111 ----------2012/10/9
2 ------- 222-----------2012/5/8
3 ------ 111-----------2012/12/12
4 ------- 111-----------2012/11/12
5---------111-----------2012/09/09
6 ------- 222-----------2012/7/9
7 ------- 333 ----------2012/4/4
Now, I want to list the users one time with their last inserted date like..
s.no---- username----- requireddate
1------- ali---------- 2012/09/09
2------- umer--------- 2012/7/9
3------- raza--------- 2012/4/4
I am using this query, but it shows maximum date not the latest one.
SELECT seeker.username, MAX(bloodrequest.requireddate) AS requireddate, COUNT(bloodrequest.requireddate) AS total
FROM seeker
JOIN bloodrequest
ON seeker.seeker_nic = bloodrequest.seeker_nic
GROUP BY seeker.username
This shows the maximum date, and it shows total dates. For example, 111 has total "4", but I don't know how to show the last inserted date... I am new in PHP, please help me. :(
Thanks in advance!

Very simple but you will need to use subselect - acquire row with last id (this will work only if you have correct indexing - i suppose you have).
Example:
SELECT seeker_nic, username,
(SELECT `requiredate` FROM `requestblood` WHERE `seeker_nic`=`seeker`.`seeker_nic` ORDER BY `id` DESC LIMIT 1) as `last_requiredate`
FROM `seeker`

Related

Emulate search and get row number of returned row (from total)

I'm a begginer in MySQL and have been searching for a solution for this problem for a few hours now. I found a few answers, but can't seem to implement them.
Basically, heres what I want to do:
I want to find how a user from from a given country would rank compared to other users from the same country when they are ranked by ID
For example:
Joe is ID 10 and is from the US
There are 100 users from the US
Result: Joe ranks 10th
How would I convert this to an MySQL query?
Thank you in advance.
Create 2 user variables,eg,running & previous which gets the previous rank number and accordingly calculate the rank number of the country by incrementing the current value by 1.
select u.id,u.country,u.rank
from (
select u1.id,u1.country,
#running:=if(#previous=concat(u1.id,u1.country),#running,0) + 1 as rank,
#previous:=concat(u1.id,u1.country)
from tablename u1
order by concat(t.id,t.country)
) u;
Replace tablename with your table

Group SQL rows by column value without flattening [duplicate]

Is it possible to sort in MySQL by "order by" using a predefined set of column values (ID) like order by (ID=1,5,4,3) so I would get records 1, 5, 4, 3 in that order out?
UPDATE: Why I need this...
I want my records to change sort randomly every 5 minutes. I have a cron task to update the table to put different, random sort order in it.
There is just one problem! PAGINATION.
I will have visitors who come to my page, and I will give them the first 20 results. They will wait 6 minutes, go to page 2 and have the wrong results as the sort order has already changed.
So I thought that if I put all the IDs into a session on page 2, we get the correct records even if the sorting had already changed.
Is there any other better way to do this?
You can use ORDER BY and FIELD function.
See http://lists.mysql.com/mysql/209784
SELECT * FROM table ORDER BY FIELD(ID,1,5,4,3)
It uses Field() function, Which "Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found" according to the documentation. So actually you sort the result set by the return value of this function which is the index of the field value in the given set.
You should be able to use CASE for this:
ORDER BY CASE id
WHEN 1 THEN 1
WHEN 5 THEN 2
WHEN 4 THEN 3
WHEN 3 THEN 4
ELSE 5
END
On the official documentation for mysql about ORDER BY, someone has posted that you can use FIELD for this matter, like this:
SELECT * FROM table ORDER BY FIELD(id,1,5,4,3)
This is untested code that in theory should work.
SELECT * FROM table ORDER BY id='8' DESC, id='5' DESC, id='4' DESC, id='3' DESC
If I had 10 registries for example, this way the ID 1, 5, 4 and 3 will appears first, the others registries will appears next.
Normal exibition
1
2
3
4
5
6
7
8
9
10
With this way
8
5
4
3
1
2
6
7
9
10
There's another way to solve this. Add a separate table, something like this:
CREATE TABLE `new_order` (
`my_order` BIGINT(20) UNSIGNED NOT NULL,
`my_number` BIGINT(20) NOT NULL,
PRIMARY KEY (`my_order`),
UNIQUE KEY `my_number` (`my_number`)
) ENGINE=INNODB;
This table will now be used to define your own order mechanism.
Add your values in there:
my_order | my_number
---------+----------
1 | 1
2 | 5
3 | 4
4 | 3
...and then modify your SQL statement while joining this new table.
SELECT *
FROM your_table AS T1
INNER JOIN new_order AS T2 on T1.id = T2.my_number
WHERE ....whatever...
ORDER BY T2.my_order;
This solution is slightly more complex than other solutions, but using this you don't have to change your SELECT-statement whenever your order criteriums change - just change the data in the order table.
If you need to order a single id first in the result, use the id.
select id,name
from products
order by case when id=5 then -1 else id end
If you need to start with a sequence of multiple ids, specify a collection, similar to what you would use with an IN statement.
select id,name
from products
order by case when id in (30,20,10) then -1 else id end,id
If you want to order a single id last in the result, use the order by the case. (Eg: you want "other" option in last and all city list show in alphabetical order.)
select id,city
from city
order by case
when id = 2 then city else -1
end, city ASC
If i had 5 city for example, i want to show the city in alphabetical order with "other" option display last in the dropdown then we can use this query.
see example other are showing in my table at second id(id:2) so i am using "when id = 2" in above query.
record in DB table:
Bangalore - id:1
Other - id:2
Mumbai - id:3
Pune - id:4
Ambala - id:5
my output:
Ambala
Bangalore
Mumbai
Pune
Other
SELECT * FROM TABLE ORDER BY (columnname,1,2) ASC OR DESC

How to fetch value according to the proper order using PHP and Mysql

I need one help.I need to fetch value according to the one certain order using PHP and Mysql.I am explaining my table below.
db_subcategory:
id cat_id name order
1 10 happy hour 1
2 10 wine 3
3 10 water 2
4 11 pizza 1
5 10 beer 2
Here i need query in Mysql to fetch all name whose cat_id=10 according to the order.It should come as per order1,2,3... if for order value 2 there are two set of name,in this case the name will come alphabetically.Please help me.
SELECT name
FROM db_subcategory
WHERE cat_id = 10
ORDER BY `order`, name
EDIT: It might also needed to add backticks for order because it is a keyword.
Demo.
Order by with two columns will do.
select * from db_subcategory where cat_id = 10 order by order, name

show matching mysql table results only once?

hi I'm looking for a way to only show a matching set of mysql results only once. can anyone tell me how to do this?
here's an example of what i'm trying to achieve:
id | profile_id | viewed_profile_id | date_viewed
1 4 7 00:00:00
2 5 6 00:00:00
1 4 7 00:00:00
so if profile_id and viewed_profile_id match then to only show one result for those matching columns rather than twice or three times or however many times it appears in the database?
Use the DISTINCT keyword:
SELECT DISTINCT id, profile_id, viewed_profile_id, date_viewed
FROM myTable
This will show only one row for each unique combination of the columns selected.
Or, reading into your question a lot (since you only want to match profile_id and viewed_profile_id), if you want to show the latest date viewed for each viewer, you can use GROUP BY and select the MAX date viewed. I am also assuming there is data in date_viewed and it is sortable:
SELECT profile_id, viewed_profile_id, MAX(date_viewed)
FROM myTable
GROUP BY profile_id, viewed_profile_id
DISTINCT helps to eliminate duplicates. If a query returns a result that contains duplicate rows, you can remove duplicates to produce a result set in which every row is unique. To do this, include the keyword DISTINCT after SELECT and before the output column list
http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html
SELECT DISTINCT(` profile_id`),`viewed_profile_id`,`id`,`date_viewed` FROM `tableName` GROUP BY `viewed_profile_id`
try this:
$query = "SELECT * FROM TABLENAME WHERE profile_id = '$PROFILEIDVALUE' AND viewed_profile_id = '$VIEWEDIDVALUE' LIMIT 0, 1"
Depending upon the ORDER you want use can use ORDER BY id DESC/ASC
I hope this would be useful

Select Mulitple Records based on One record's column value

I have a table which contains related records (multiple revisions of the same record). Each record has a string field that resembles a date (date, time, and microtime). I want to select all records that are older than a specific date. If a record has a related record newer than the specific date, I do not want to select any of those related records. Any ideas for that select statement? Eventually, it will be a REMOVE statement.
Edit: Some Sample Rows
id shared_id date type other_data...
1 2 2010-01-01 01:02:03.1234567 original ...
2 3 2010-01-15 11:12:03.1234733 original ...
3 2 2010-02-01 03:04:04.5465654 amendment ...
If my cut-off date was "2010-01-31", I would want to select id #2 only because id #1 has an amendment newer than the cut-off date.
I found this link helping me generate the select statement.
SELECT DISTINCT T.shared_id,T.date,T.id
FROM table T WHERE T.date = (
SELECT MAX( date ) FROM table WHERE shared_id = T.shared_id )
AND T.date < 'my_cut_off_date_string'
This seems to work for me. Thanks for everyone's help.
Maybe you can try the DATEDIFF() function, check this out:
Link 1
Or this one: Link 2
Or maybe you can try the classic query (SELECT FROM table WHERE data <= anotherdata), but in this case you need to convert both data in timestamp format
DELETE from tablename where relatedField = 'relatedValue' AND dateField <= dateToDeleteFrom
Something along those lines should do what you need it to do, if I understand your scenario. If you provide a sample data set I can adjust the statement to more accurately represent your need, but I think this is a good starting point.
HTH,
Jc

Categories