tbl_contacts: -
user_id - int
contact_id - int
first_name - varchar
last_name - varchar
date_backup - TIMESTAMP
I am having lots of data and i want to get the latest one from the database.
Currently I am having data of 2 different dates, 1 is 2014-02-12 04:47:39 and another is 2014-01-12 04:47:39. I am having total 125 records from which 5 are of 2014-01-12 04:47:39 date and rest are of 2014-02-12 04:47:39. I am using below query to get the latest date data but its returning all the data somehow. I am trying since long and unable to successfully achieve my goal. If anyone has any idea please kindly help me.
Query
SELECT `contact_id`, `user_id`, `date_backup`, `first_name`, `last_name`
FROM tbl_contacts WHERE `date_backup` IN (
SELECT MAX(`date_backup`)
FROM tbl_contacts WHERE `user_id`= 1 GROUP BY `contact_id`
)
ORDER BY `contact_id`ASC, `date_backup` DESC
By using ORDER BY date_backup DESC, I am getting the old data at the end of list. But i just don't want the old date record at all if new date record is available.
user MySql UNIX_TIMESTAMP() with ORDER BY Clause.
SELECT `contact_id`, `user_id`, `date_backup`, `first_name`, `last_name`
FROM tbl_contacts WHERE `date_backup` IN (
SELECT MAX(`date_backup`)
FROM tbl_contacts WHERE `user_id`= 1 GROUP BY `contact_id`
)
ORDER BY UNIX_TIMESTAMP(`date_backup`) DESC, `contact_id`ASC
If require change all date_backup with UNIX_TIMESTAMP(`date_backup`)
LIMIT will do the trick in MySQL database (in other databases it would probably be TOP clause). So use LIMIT 10:
SELECT TOP 1 `contact_id`, `user_id`, `date_backup`, `first_name`, `last_name`
FROM tbl_contacts WHERE `date_backup` IN (
SELECT MAX(`date_backup`)
FROM tbl_contacts WHERE `user_id`= 1 GROUP BY `contact_id`
)
ORDER BY `contact_id`ASC, `date_backup` DESC
LIMIT 10
If you want ten of the most recent ones.
The guide for the LIMIT clause can be found at MySQL reference
Similar kind of issue
Just add LIMIT 1 at the end of your query to select only the first line of results.
Related
My work is for an appointment system:
I have two tables:
Times(hour varchar);
Reservations(time varchar, date varchar);
Times table have all the times a store is open (as strings) from 8 to 6pm (08:00,08:30,09:00,etc..)
Reservation has the times reserved.
The store has 3 employees that can do an appointment simultaneously, so 3 client can reserve at 10:00am per example.
My goal is to return the list of times that aren't reserved but on one condition: If a time has been reserved less than 3 times it can still be reserved. I tried this query
SELECT `hour` FROM `times` WHERE `hour` NOT IN (SELECT `time` FROM `reservations` WHERE `date` = '$date' HAVING COUNT(`time`)>=3);
The problem is this returns null if there are no reserved times, but i cant understand why.. If the subquery returns null, the first query not in subquery(null) must return all the times in the Times table right? Its giving me empty rows... Anyone know why?
This query:
SELECT `time`
FROM `reservations`
WHERE `date` = '$date'
GROUP BY `time`
HAVING COUNT(*) >= 3
returns the list of times that are reserved under your condition.
So use a LEFT JOIN of Times to that query and return only the unmatched rows:
SELECT t.`hour`
FROM `times` t LEFT JOIN (
SELECT `time`
FROM `reservations`
WHERE `date` = '$date'
GROUP BY `time`
HAVING COUNT(*) >= 3
) r on r.time = t.`hour`
WHERE r.time IS NULL
If subquery returns null, then IN operator will always give you null as result. If you want to get results ensure you don't have nulls in subquery or make subquery return empty set. I tried it on SQL server.
I'm doing a basic SQL select query which returns a set of results. I want a specific row which the entry "Fee" to be put at the top of the results, then the rest.
Something like:
SELECT * FROM tbl ORDER By Charges = Fee DESC, Charges DESC
Can anyone help?
You could try this :
SELECT * from tbl ORDER BY CASE WHEN Charges = 'Fee' THEN 0 ELSE 1 END, Charges DESC;
I think you'd have a use a UNION query. ORDER BY doesn't support this kind of thing by default as far as I know.
Something like this:
SELECT * FROM tbl WHERE Charges = 'Fee'
UNION
SELECT * FROM tbl ORDER BY Charges DESC
You would have to use ORDER BY with a FIELD attribute, which would then order by those first.
As I don't have your table definitions, I have throw one together here http://sqlfiddle.com/#!9/91376/13
For sake of it disappearing, the script pretty much consists of;
CREATE TABLE IF NOT EXISTS `tbl` (
`id` int(6) unsigned AUTO_INCREMENT,
`Name` char(6) not null,
`Charges` char(10) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `tbl` (`Name`, `Charges`)
VALUES ('One', 'Fee'), ('Two', 'Charge'), ('Three', 'Charge'),
('Four', 'Charge'), ('Five', 'Fee'), ('Six', 'Fee'),
('Seven', 'Invoice'), ('Eight', 'Fee'), ('Nine', 'Invoice'),
('Ten', 'Invoice');
SELECT *
FROM tbl
ORDER BY FIELD(`Charges`, 'Charge') DESC
;
Which returns:
id Name Charges
2 Two Charge
3 Three Charge
4 Four Charge
1 One Fee
9 Nine Invoice
8 Eight Fee
7 Seven Invoice
6 Six Fee
5 Five Fee
10 Ten Invoice
So, to directly answer your question, your query would be;
SELECT *
FROM tbl
ORDER BY FIELD(Charges, 'Fee') DESC
edit : Viewable, sorted by Charges = Fee here : http://sqlfiddle.com/#!9/91376/15
SELECT * FROM tbl ORDER By FIELD(Charges, 'Fee') DESC
You can use something like the above. Where Charges is the field and fee the specific value. That way you can keep it simple.
I am writing the below specified query which has no error but doesn't fetch me the correct record which matches current date of server, on other part it shows me old records
My Mysql Query:
select news_title,
full_url,
source_site,
date_added,
`category`
from tbl_urlLog
where category like '%enter%'
or category like '%hollywood%'
or category like '%bollywood%'
or category like '%movies%'
or category like '%film%'
and date (`date_added`) = date (CURDATE())
group by `source_site`
order by `date_added` desc LIMIT 3
I am guessing you want to group together all the ORs using parentheses. Also, curdate() already is date no need to call date() on it.
select news_title,
full_url,
source_site,
date_added,
`category`
from tbl_urlLog
where (
category like '%enter%'
or category like '%hollywood%'
or category like '%bollywood%'
or category like '%movies%'
or category like '%film%'
)
and date (`date_added`) = CURDATE()
group by `source_site`
order by `date_added` desc LIMIT 3
I have a services table with the following column-rows on a MySQL database
`id` `service_rendered` `created_at`
1 repair 2016-11-19 14:40:56
2 install 2016-11-19 14:40:58
3 repair 2016-11-19 14:44:27
4 install 2016-11-19 14:50:35
I'm trying to count the number of services and the last date/time it was rendered. Column created_at is a datetime type.
The SQL statement that I'm running is:
SELECT COUNT(`service_rendered`) as `count_service`, `service_rendered`, `created_at` as `last_rendered`
FROM services
WHERE `id` IN (1,2,3)
GROUP BY `service_rendered`
ORDER BY `created_at` DESC
But what I'm getting is:
`count_service` `service_rendered` `last_rendered`
2 repair 2016-11-19 14:40:56
1 install 2016-11-19 14:40:58
How do I write my SQL so that I am able to get 2016-11-19 14:44:27 on repair?
You can use the following solution using MAX on the created_at column:
SELECT COUNT(`service_rendered`) AS `count_service`, `service_rendered`, MAX(`created_at`) AS `last_rendered`
FROM services
WHERE `id` IN (1,2,3)
GROUP BY `service_rendered`
ORDER BY `last_rendered` DESC
demo: http://sqlfiddle.com/#!9/3906b7/2
You want to ORDER BY created_at DESC?
You have to use the alias of the column last_rendered, so replace ORDER BY created DESC with ORDER BY last_rendered DESC
You have to select the max(created_date) instead of created_date for last_rendered.
Then your query will become
select
count(service_rendered) as count_service,
service_rendered,
max(created_at) as last_rendered
from
services
group by service_rendered
order by created_at desc
I have a table that has an integer id (primary key) and timestamp date added columns (among others).
what would the syntax to extract the id values for the ten most recent "date added" values look like?
If we go by the title of your question (10 most recent rows):
SELECT `id`
FROM `table`
ORDER BY `date added` DESC
LIMIT 10
If we go by what you say in your question (10 most recent values of date added):
SELECT `id`
FROM `table`
WHERE `date added` IN ( SELECT DISTINCT `date added`
FROM `table`
ORDER BY `date added` DESC
LIMIT 10 )
As I noted in my comments, I use Transact-SQL primarily so you might need to adjust for any gaps in my MySQL knowledge.
SELECT id
FROM `table`
ORDER BY `date added` DESC LIMIT 10
;
If you have an auto incremented primary key you could also order by id:
SELECT `id`
FROM `table`
ORDER BY `id` DESC
LIMIT 10
The advantage is that id already has a index so you can sort by it very fast. But you need to be sure that you don't mess around with the id so it is always in the right order.
If you use date added anyway you should create an index for it. But the table will use a little bit more space this way.
SELECT id FROM `table` ORDER BY `date added` DESC LIMIT 10