ROOM TABLE
CREATE TABLE `room` (
`id` int(11) NOT NULL,
`price` double NOT NULL,
`type` varchar(255) NOT NULL,
`photo` varchar(255) NOT NULL,
`max_capacity` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `room` (`id`, `price`, `type`, `photo`, `max_capacity`) VALUES (1, 25, 'Suite', 'something.jpg', 3);
INSERT INTO `room` (`id`, `price`, `type`, `photo`, `max_capacity`) VALUES (2, 20, 'Single', 'something.jpg', 1);
INSERT INTO `room` (`id`, `price`, `type`, `photo`, `max_capacity`) VALUES (3, 250, 'Family Suite', 'something.jpg', 8);
INSERT INTO `room` (`id`, `price`, `type`, `photo`, `max_capacity`) VALUES (4, 20, 'Twin', 'something.jpg', 2);
INSERT INTO `room` (`id`, `price`, `type`, `photo`, `max_capacity`) VALUES (5, 20, 'Twin', 'something.jpg', 2);
INSERT INTO `room` (`id`, `price`, `type`, `photo`, `max_capacity`) VALUES (6, 25, 'Suite', 'something.jpg', 3);
ALTER TABLE `room`
ADD PRIMARY KEY (`id`);
ORDERS TABLE
CREATE TABLE `orders` (
`id` int(11) NOT NULL,
`checkin` date NOT NULL,
`checkout` date NOT NULL,
`id_user` int(11) NOT NULL,
`id_room` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `orders` (`id`, `checkin`, `checkout`, `id_user`, `id_room`) VALUES
(1, '2023-01-12', '2023-01-13', 1, 1),
(2, '2023-01-11', '2023-01-15', 1, 2);
ALTER TABLE `orders`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;
I tried the following:
SELECT id,type FROM room WHERE (SELECT \* FROM orders WHERE (2023-01-12 NOT BETWEEN `checkin` AND `checkout`) AND (2023-01-13 NOT BETWEEN `checkin` AND `checkout`));
I expect to get all the room with id (2-6) and the id = 1 to not be showed if the reservation is made in the interval of 12.01.2023(checkin choosen by client x) and 13.01.2023(checkout choosen by client x).
I would appreciate your help alot! THANK YOU!
Try this
SELECT id, type
FROM room
WHERE id NOT IN (
SELECT id_room
FROM orders
WHERE checkin >= '2023-01-12' AND checkout <= '2023-01-13'
);
I have two query to get count and sum of rate for unique ip's.
Query one groups by date and query two groups by country
This is the table
DROP TABLE IF EXISTS `stats`;
CREATE TABLE IF NOT EXISTS `stats` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` int(5) UNSIGNED NOT NULL,
`country` int(3) UNSIGNED NOT NULL,
`user_ip` int(50) UNSIGNED NOT NULL,
`timestamp` int(10) UNSIGNED NOT NULL,
`rate` int(7) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `stats`
--
INSERT INTO `stats` (`id`, `user_id`, `country`, `user_ip`, `timestamp`, `rate`) VALUES
(1, 1, 1, 1111111111, 1489999983, 15000),
(2, 1, 2, 1111111112, 1489999984, 10000),
(3, 1, 1, 1111111111, 1489999985, 10000),
(4, 1, 1, 1111111111, 1490086333, 10000),
(5, 1, 2, 1111111111, 1490086334, 10000),
(6, 1, 1, 1111111121, 1490086335, 10000);
These are the queries I am using to get data
To get sum of rates based on date I use following query
SELECT COUNT(`user_ip`) AS `count`, SUM(`rate`) AS `rate`, `timestamp`
FROM (
SELECT DISTINCT `user_ip`, `rate`, `timestamp`
FROM `stats`.`stats`
WHERE `user_id`=? `timestamp`>=? AND `timestamp`<=?
GROUP BY DATE(FROM_UNIXTIME(`timestamp`)),`user_ip`
) c
GROUP BY DATE(FROM_UNIXTIME(`timestamp`))
Result
date count rate
20-03-2017 2 25000
21-03-2017 2 20000
To get sum of rates based on country I use following query
SELECT COUNT(`user_ip`) AS `count`, SUM(`rate`) AS `rate`, `timestamp`, `country`
FROM (
SELECT DISTINCT `user_ip`, `rate`, `timestamp`, `country`
FROM `stats`.`stats`
WHERE `user_id`=? `timestamp`>=? AND `timestamp`<=?
GROUP BY DATE(FROM_UNIXTIME(`timestamp`)),`user_ip`
) c
GROUP BY `country`
Result
country count rate
1 3 35000
2 1 10000
Since these two query are nearly same and fetches same rows from table is it possible to get both result from single query instead of two query.
Also please suggest if it can be be done in PHP effectively than MYSQL.
Thanks
Try this in php
$country="";
$groupByCondition="DATE(FROM_UNIXTIME(`timestamp`))";
if(/*BasedOnCountry*/){
$country=", `country`";
$groupByCondition = "`country`";
}
$query= "SELECT COUNT(`user_ip`) AS `count`, SUM(`rate`) AS `rate`, `timestamp`"+ $country +"
FROM (
SELECT DISTINCT `user_ip`, `rate`, `timestamp`"+ $country +"
FROM `stats`.`stats`
WHERE `user_id`=? `timestamp`>=? AND `timestamp`<=?
GROUP BY DATE(FROM_UNIXTIME(`timestamp`)),`user_ip`
) c
GROUP BY "+ $groupByCondition ;
//execute the query and get the results
Only way I have been able to achieve my result was to create something that is in my eyes very ugly, it takes ages to process the query but was unable to come up with anything simpler that that:
SELECT
*, COUNT(Application.id) AS count,
(SELECT id FROM applications WHERE identifier = Application.identifier AND platform = Application.platform ORDER BY created DESC LIMIT 1) AS id,
(SELECT location FROM applications WHERE identifier = Application.identifier AND platform = Application.platform ORDER BY created DESC LIMIT 1) AS location,
(SELECT name FROM applications WHERE identifier = Application.identifier AND platform = Application.platform ORDER BY created DESC LIMIT 1) AS name,
(SELECT version FROM applications WHERE identifier = Application.identifier AND platform = Application.platform ORDER BY created DESC LIMIT 1) AS version,
(SELECT created FROM applications WHERE identifier = Application.identifier AND platform = Application.platform ORDER BY created DESC LIMIT 1) AS created
FROM `enterpriseappstore`.`applications` AS `Application`
WHERE 1 = 1
GROUP BY `Application`.`identifier`, `Application`.`platform`
ORDER BY `Application`.`name` ASC, `Application`.`created` DESC
Please note the ORDER BY created DESC LIMIT 1 in every subquery that makes sure only the latest application has been selected ... everything is in cakePHP project here (like 97):
https://github.com/Ridiculous-Innovations/EnterpriseAppStore/blob/master/web/app/Model/Application.php
For your reference, there is a table and some sample data, the iDeviant app with Latest in it's name should be the one on the top of the group:
CREATE TABLE `applications` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`identifier` varchar(150) NOT NULL,
`url` varchar(255) NOT NULL,
`platform` tinyint(2) unsigned NOT NULL,
`version` varchar(15) NOT NULL,
`size` bigint(20) unsigned NOT NULL DEFAULT '0',
`sort` int(5) unsigned NOT NULL DEFAULT '1000',
`config` text NOT NULL,
`location` tinyint(2) unsigned NOT NULL DEFAULT '0',
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`,`identifier`,`platform`,`sort`),
KEY `version` (`version`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Dumping data for table `applications`
--
INSERT INTO `applications` (`id`, `name`, `identifier`, `url`, `platform`, `version`, `size`, `sort`, `config`, `location`, `created`, `modified`) VALUES
(1, 'iDeviant', 'com.fuerteint.iDeviant', '', 1, '4.0', 1059404, 1000, '{"plist":{"CFBundleDisplayName":"iDeviant","CFBundleName":"iDeviant","DTXcode":"0501","DTSDKName":"iphoneos7.0","UISupportedInterfaceOrientations~ipad":["UIInterfaceOrientationPortrait","UIInterfaceOrientationPortraitUpsideDown","UIInterfaceOrientationLandscapeLeft","UIInterfaceOrientationLandscapeRight"],"CFBundleIcons~ipad":{"CFBundlePrimaryIcon":{"CFBundleIconFiles":["AppIcon29x29","AppIcon40x40","AppIcon60x60","AppIcon76x76"]}},"DTSDKBuild":"11B508","CFBundleDevelopmentRegion":"en","CFBundleVersion":"1.0","BuildMachineOSBuild":"13A603","DTPlatformName":"iphoneos","CFBundleShortVersionString":"4.0","CFBundlePackageType":"APPL","CFBundleSupportedPlatforms":["iPhoneOS"],"CFBundleInfoDictionaryVersion":"6.0","UIRequiredDeviceCapabilities":["armv7"],"DTCompiler":"com.apple.compilers.llvm.clang.1_0","CFBundleExecutable":"iDeviant","UILaunchImages":[{"UILaunchImageOrientation":"Portrait","UILaunchImageName":"LaunchImage-700-568h","UILaunchImageSize":"{320, 568}","UILaunchImageMinimumOSVersion":"7.0"}],"CFBundleResourceSpecification":"ResourceRules.plist","MinimumOSVersion":"7.0","UIDeviceFamily":[1],"UIViewControllerBasedStatusBarAppearance":false,"DTXcodeBuild":"5A2053","CFBundleIdentifier":"com.fuerteint.iDeviant","UIAppFonts":["FontAwesome.ttf"],"CFBundleSignature":"????","DTPlatformVersion":"7.0","CFBundleIcons":{"CFBundlePrimaryIcon":{"CFBundleIconFiles":["AppIcon29x29","AppIcon40x40","AppIcon60x60"]}},"LSRequiresIPhoneOS":true,"UISupportedInterfaceOrientations":["UIInterfaceOrientationPortrait","UIInterfaceOrientationLandscapeLeft","UIInterfaceOrientationLandscapeRight"],"DTPlatformBuild":"11B508"},"icons":["AppIcon29x29#2x.png","AppIcon29x29#2x~ipad.png","AppIcon29x29~ipad.png","AppIcon40x40#2x.png","AppIcon40x40#2x~ipad.png","AppIcon40x40~ipad.png","AppIcon60x60#2x.png","AppIcon76x76#2x~ipad.png","AppIcon76x76~ipad.png"],"provisioning":"enterprise","author":"","description":"","fullDescription":""}', 1, '2013-11-19 14:36:01', '2013-11-19 14:36:01'),
(29, 'removeya-debug', 'cz.ursimon.removya', '', 3, '1.0', 536699, 1000, '{"version-code":"1","install-location":"0","min-sdk-version":"8","screen-sizes":{"anydensity":"true","smallscreens":"true","normalscreens":"true","largescreens":"true","resizeable":"true"},"permissions":[],"author":"","description":"","fullDescription":""}', 0, '2013-11-20 09:40:35', '2013-11-20 09:40:35'),
(30, 'iDeviant', 'com.fuerteint.iDeviant', '', 1, '4.0', 1059404, 1000, '{"plist":{"CFBundleDisplayName":"iDeviant","CFBundleName":"iDeviant","DTXcode":"0501","DTSDKName":"iphoneos7.0","UISupportedInterfaceOrientations~ipad":["UIInterfaceOrientationPortrait","UIInterfaceOrientationPortraitUpsideDown","UIInterfaceOrientationLandscapeLeft","UIInterfaceOrientationLandscapeRight"],"CFBundleIcons~ipad":{"CFBundlePrimaryIcon":{"CFBundleIconFiles":["AppIcon29x29","AppIcon40x40","AppIcon60x60","AppIcon76x76"]}},"DTSDKBuild":"11B508","CFBundleDevelopmentRegion":"en","CFBundleVersion":"1.0","BuildMachineOSBuild":"13A603","DTPlatformName":"iphoneos","CFBundleShortVersionString":"4.0","CFBundlePackageType":"APPL","CFBundleSupportedPlatforms":["iPhoneOS"],"CFBundleInfoDictionaryVersion":"6.0","UIRequiredDeviceCapabilities":["armv7"],"DTCompiler":"com.apple.compilers.llvm.clang.1_0","CFBundleExecutable":"iDeviant","UILaunchImages":[{"UILaunchImageOrientation":"Portrait","UILaunchImageName":"LaunchImage-700-568h","UILaunchImageSize":"{320, 568}","UILaunchImageMinimumOSVersion":"7.0"}],"CFBundleResourceSpecification":"ResourceRules.plist","MinimumOSVersion":"7.0","UIDeviceFamily":[1],"UIViewControllerBasedStatusBarAppearance":false,"DTXcodeBuild":"5A2053","CFBundleIdentifier":"com.fuerteint.iDeviant","UIAppFonts":["FontAwesome.ttf"],"CFBundleSignature":"????","DTPlatformVersion":"7.0","CFBundleIcons":{"CFBundlePrimaryIcon":{"CFBundleIconFiles":["AppIcon29x29","AppIcon40x40","AppIcon60x60"]}},"LSRequiresIPhoneOS":true,"UISupportedInterfaceOrientations":["UIInterfaceOrientationPortrait","UIInterfaceOrientationLandscapeLeft","UIInterfaceOrientationLandscapeRight"],"DTPlatformBuild":"11B508"},"icons":["AppIcon29x29#2x.png","AppIcon29x29#2x~ipad.png","AppIcon29x29~ipad.png","AppIcon40x40#2x.png","AppIcon40x40#2x~ipad.png","AppIcon40x40~ipad.png","AppIcon60x60#2x.png","AppIcon76x76#2x~ipad.png","AppIcon76x76~ipad.png"],"provisioning":"enterprise"}', 0, '2013-11-20 21:08:09', '2013-11-20 21:08:09'),
(31, 'iDeviant', 'com.fuerteint.iDeviant', '', 1, '4.0', 1059404, 1000, '{"plist":{"CFBundleDisplayName":"iDeviant","CFBundleName":"iDeviant","DTXcode":"0501","DTSDKName":"iphoneos7.0","UISupportedInterfaceOrientations~ipad":["UIInterfaceOrientationPortrait","UIInterfaceOrientationPortraitUpsideDown","UIInterfaceOrientationLandscapeLeft","UIInterfaceOrientationLandscapeRight"],"CFBundleIcons~ipad":{"CFBundlePrimaryIcon":{"CFBundleIconFiles":["AppIcon29x29","AppIcon40x40","AppIcon60x60","AppIcon76x76"]}},"DTSDKBuild":"11B508","CFBundleDevelopmentRegion":"en","CFBundleVersion":"1.0","BuildMachineOSBuild":"13A603","DTPlatformName":"iphoneos","CFBundleShortVersionString":"4.0","CFBundlePackageType":"APPL","CFBundleSupportedPlatforms":["iPhoneOS"],"CFBundleInfoDictionaryVersion":"6.0","UIRequiredDeviceCapabilities":["armv7"],"DTCompiler":"com.apple.compilers.llvm.clang.1_0","CFBundleExecutable":"iDeviant","UILaunchImages":[{"UILaunchImageOrientation":"Portrait","UILaunchImageName":"LaunchImage-700-568h","UILaunchImageSize":"{320, 568}","UILaunchImageMinimumOSVersion":"7.0"}],"CFBundleResourceSpecification":"ResourceRules.plist","MinimumOSVersion":"7.0","UIDeviceFamily":[1],"UIViewControllerBasedStatusBarAppearance":false,"DTXcodeBuild":"5A2053","CFBundleIdentifier":"com.fuerteint.iDeviant","UIAppFonts":["FontAwesome.ttf"],"CFBundleSignature":"????","DTPlatformVersion":"7.0","CFBundleIcons":{"CFBundlePrimaryIcon":{"CFBundleIconFiles":["AppIcon29x29","AppIcon40x40","AppIcon60x60"]}},"LSRequiresIPhoneOS":true,"UISupportedInterfaceOrientations":["UIInterfaceOrientationPortrait","UIInterfaceOrientationLandscapeLeft","UIInterfaceOrientationLandscapeRight"],"DTPlatformBuild":"11B508"},"icons":["AppIcon29x29#2x.png","AppIcon29x29#2x~ipad.png","AppIcon29x29~ipad.png","AppIcon40x40#2x.png","AppIcon40x40#2x~ipad.png","AppIcon40x40~ipad.png","AppIcon60x60#2x.png","AppIcon76x76#2x~ipad.png","AppIcon76x76~ipad.png"],"provisioning":"enterprise"}', 0, '2013-11-20 21:08:22', '2013-11-20 21:08:22'),
(32, 'iDeviant Latest', 'com.fuerteint.iDeviant', '', 1, '5.0', 1059404, 1000, '{"plist":{"CFBundleDisplayName":"iDeviant","CFBundleName":"iDeviant","DTXcode":"0501","DTSDKName":"iphoneos7.0","UISupportedInterfaceOrientations~ipad":["UIInterfaceOrientationPortrait","UIInterfaceOrientationPortraitUpsideDown","UIInterfaceOrientationLandscapeLeft","UIInterfaceOrientationLandscapeRight"],"CFBundleIcons~ipad":{"CFBundlePrimaryIcon":{"CFBundleIconFiles":["AppIcon29x29","AppIcon40x40","AppIcon60x60","AppIcon76x76"]}},"DTSDKBuild":"11B508","CFBundleDevelopmentRegion":"en","CFBundleVersion":"1.0","BuildMachineOSBuild":"13A603","DTPlatformName":"iphoneos","CFBundleShortVersionString":"4.0","CFBundlePackageType":"APPL","CFBundleSupportedPlatforms":["iPhoneOS"],"CFBundleInfoDictionaryVersion":"6.0","UIRequiredDeviceCapabilities":["armv7"],"DTCompiler":"com.apple.compilers.llvm.clang.1_0","CFBundleExecutable":"iDeviant","UILaunchImages":[{"UILaunchImageOrientation":"Portrait","UILaunchImageName":"LaunchImage-700-568h","UILaunchImageSize":"{320, 568}","UILaunchImageMinimumOSVersion":"7.0"}],"CFBundleResourceSpecification":"ResourceRules.plist","MinimumOSVersion":"7.0","UIDeviceFamily":[1],"UIViewControllerBasedStatusBarAppearance":false,"DTXcodeBuild":"5A2053","CFBundleIdentifier":"com.fuerteint.iDeviant","UIAppFonts":["FontAwesome.ttf"],"CFBundleSignature":"????","DTPlatformVersion":"7.0","CFBundleIcons":{"CFBundlePrimaryIcon":{"CFBundleIconFiles":["AppIcon29x29","AppIcon40x40","AppIcon60x60"]}},"LSRequiresIPhoneOS":true,"UISupportedInterfaceOrientations":["UIInterfaceOrientationPortrait","UIInterfaceOrientationLandscapeLeft","UIInterfaceOrientationLandscapeRight"],"DTPlatformBuild":"11B508"},"icons":["AppIcon29x29#2x.png","AppIcon29x29#2x~ipad.png","AppIcon29x29~ipad.png","AppIcon40x40#2x.png","AppIcon40x40#2x~ipad.png","AppIcon40x40~ipad.png","AppIcon60x60#2x.png","AppIcon76x76#2x~ipad.png","AppIcon76x76~ipad.png"],"provisioning":"enterprise"}', 0, '2013-11-20 21:08:35', '2013-11-20 21:08:35');
have you tried this:
SELECT FROM_UNIXTIME(SUBSTR(MIN(CONCAT(LPAD(UNIX_TIMESTAMP(`created`),15,'0'),`name`)),1,15)) AS `date`,
SUBSTR(MIN(CONCAT(LPAD(UNIX_TIMESTAMP(`created`),15,'0'),`name`)),16) AS `name`
FROM `applications`
GROUP BY `applications`.`identifier`, `applications`.`platform`;
The idea is:
since we sort by created within every group, we start from this column by converting it to timestamp. UNIX_TIMESTAMP(created)
pad it on the left with zeroes to fixed length, say 15. I don't think we'll have timestamps >15 digits in the nearest future, so we're safe
CONCAT it with the name. Place name on the right side of concatenation. This is for later SUBSTRING'ing of it from this concatenation
sort by this concatenation ascending (MIN), so effectively we will sort by created ASC within group of GROUP BY applications.identifier, applications.platform
now we have the earliest created along with the name valuable info on the right for each group of pplications.identifier, applications.platform
SUBSTRING the concatenated info, get two parts 1-15 (created) and 16-end (name), select them as two different columns
I have the joy of recreating the phone, by building a customized messaging system in PHP that uses an API to send and receive messages.
I'm trying to emulate the functionality found in Facebook messaging on their desktop site.
[Col 1] [Col 2]
A list of the Conversation View.
latest messages
received in order
of Newest to oldest
I am having issues with the Query for the first column.
I currently have a table in MySQL with the following structure:
CREATE TABLE IF NOT EXISTS `History` (
`ID` int(10) NOT NULL AUTO_INCREMENT COMMENT 'MessageID',
`Sender` varchar(10) NOT NULL,
`Recipient` varchar(10) NOT NULL,
`ExtReference` int(20) DEFAULT NULL,
`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`Status` varchar(100) NOT NULL,
`userid` int(3) NOT NULL,
`Message` longtext NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=609 ;
With a sample Date set like:
INSERT INTO `History` (`ID`, `Sender`, `Recipient`, `ExtReference`, `Date`, `Status`, `userid`, `Message`) VALUES
(1, '0412345678', '0468888888', 33845909, '2013-03-17 04:17:34', '1', 11, 'Just testing....'),
(2, '0412345678', '0400222333', 33845910, '2013-03-17 04:17:35', '1', 11, 'Amazing'),
(3, '0412345678', '0411111111', 33847419, '2013-03-17 04:46:04', '1', 8, 'Nothing here to see'),
(4, '0412345678', '0400222333', 33850155, '2013-03-17 06:31:57', '1', 12, 'Hello there Mr IT Guru :-)'),
(5, '0400222333', '0412345678', 33850179, '2013-03-17 06:33:21', '1', 12, '[Write message here]'),
(6, '0412345678', '0411111111', 33955423, '2013-03-23 01:26:22', '1', 8, 'Hello Charles'),
(7, '0412345678', '0411111111', 33959071, '2013-03-23 03:08:26', '1', 13, 'Sample Message'),
(8, '0400222333', '0412345678', 33964111, '2013-03-23 05:27:51', '1', 13, 'How do I use this system?'),
(9, '0400222333', '0412345678', 34107503, '2013-03-30 03:13:38', '1', 12, 'Is this thing on?'),
(10, '0412345678', '0401411210', 34230869, '2013-03-05 00:18:09', '1', 16, 'Hello')
(In this example my number is: 0412345678).
SQL Fiddle here: http://sqlfiddle.com/#!2/29197/1/0
I have worked out how to get a list of all the unique numbers used across both the Sender and Recipient columns:
SELECT DISTINCT `Sender` AS phoneID FROM `History`
UNION
SELECT DISTINCT `Recipient` AS phoneID FROM `History`
But I can't work how to attach the latest Date and message to this data.
If I focus on either just messages sent to me or sent by me I can get somewhere with these two:
SELECT `ID`, `Sender`, `Recipient`, MAX(`Date`), `Message` FROM History
GROUP BY Sender
ORDER BY `History`.`Date` DESC
or
SELECT `ID`, `Sender`, `Recipient`, MAX(`Date`), `Message`, `Status` FROM History
GROUP BY Recipient
ORDER BY `History`.`Date` DESC
Any thoughts?
I can recreate the History table layout if needed.
I'll also need to try and join the phone number with a persons name in a Contacts table later on down the track.
Thanks
Charlie
Possibly not the best way but you could combine the two queries you have. Something like:
SELECT `ID`, `Sender`, `Recipient`,`Date`,`Message`,`Status` FROM
(
SELECT `ID`, `Sender`, `Recipient`, `Date`, `Message`,`Status` FROM History
WHERE Sender = "0412345678"
GROUP BY Sender
UNION
SELECT `ID`, `Sender`, `Recipient`, MAX(`Date`), `Message`, `Status` FROM History
WHERE Recipient = "0412345678"
GROUP BY Recipient
) res
GROUP BY res.ID
ORDER BY res.Date DESC
Note that this is for a specific number. You could remove the WHERE clauses if this wasn't needed.