MySQL - Remove duplicate records entity relationship many to many - mysql

As I can get records from multiple tables omitting duplicate, for example I have this table "code attached tables":
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for interests
-- ----------------------------
DROP TABLE IF EXISTS `interests`;
CREATE TABLE `interests` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of interests
-- ----------------------------
INSERT INTO `interests` VALUES ('1', 'Sport');
INSERT INTO `interests` VALUES ('2', 'Technology');
INSERT INTO `interests` VALUES ('3', 'Games');
INSERT INTO `interests` VALUES ('4', 'Security');
INSERT INTO `interests` VALUES ('5', 'Movies');
-- ----------------------------
-- Table structure for interests_has_user
-- ----------------------------
DROP TABLE IF EXISTS `interests_has_user`;
CREATE TABLE `interests_has_user` (
`interests_id` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`interests_id`,`user_id`),
KEY `fk_interests_has_user_user1_idx` (`user_id`),
KEY `fk_interests_has_user_interests_idx` (`interests_id`),
CONSTRAINT `fk_interests_has_user_interests` FOREIGN KEY (`interests_id`) REFERENCES `interests` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_interests_has_user_user1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of interests_has_user
-- ----------------------------
INSERT INTO `interests_has_user` VALUES ('1', '1');
INSERT INTO `interests_has_user` VALUES ('2', '1');
INSERT INTO `interests_has_user` VALUES ('3', '1');
INSERT INTO `interests_has_user` VALUES ('4', '1');
INSERT INTO `interests_has_user` VALUES ('5', '1');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`password` varchar(45) DEFAULT NULL,
`country` varchar(45) DEFAULT NULL,
`state` varchar(45) DEFAULT NULL,
`city` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'Name', 'email#email.com', '123123', '1', '1', '1');
I need to get records from the table[ user ] and the table[ interests_has_user ], where a user can have many interests at the table table[ interests_has_user ], I'm doing the query this way:
SELECT
user.id,
user.name,
user.email,
user.country,
user.state,
user.city,
interests_has_user.interests_id,
interests_has_user.user_id
FROM
user
LEFT JOIN interests_has_user
ON user.id = interests_has_user.user_id
WHERE user.id = 1;
And I throw all records of the table table[ interests_has_user ], but in all rows the user is repeated, image attached with the result.
Note: What is shaded in yellow should be empty or null fields.
What the best solution for this, use INNER JOIN, or separate consutas.
I appreciate your help, thank you very much.

INNER JOIN will not return users without interests. So it is not what you want.
If you want to lighten-up the query results you could do two queries:
First find out the user details
SELECT
user.id,
user.name,
user.email,
user.country,
user.state,
user.city
FROM
user
WHERE user.id = 1
Then the interests ids.
SELECT user.id, interests_has_user.interests_id, interests_has_user.user_id
FROM user
LEFT JOIN interests_has_user ON user.id = interests_has_user.user_id
WHERE user.id = 1

Related

Mysql find users after table pattern

I have the following five tables:
users: id, name
region: id, usersId, region
country: id, usersId, country
status: id, usersId, status
search: id, usersId, region, country, status
The search table includes the given data after what we will search in the other tables.
So, if the search-table has 5 users from 'DE', 'US', 'CH' ... with different or same zipcodes, all users from users, region, country and status should be displayed, where this pattern is true
For example:
I have 10 users in my database and the user with the user.id = 1 stores his data in search-table:
users:
id:8, "John"
search:
id: 8, usersId:1, region: 47798, country: "DE", status: "Boss"
Now i want all other user who comes from 'DE' from the region LIKE "4%" and who works as a "Boss" :-)
This is my database:
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for `country`
-- ----------------------------
DROP TABLE IF EXISTS `country`;
CREATE TABLE `country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`usersId` int(11) NOT NULL,
`country` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of `country`
-- ----------------------------
BEGIN;
INSERT INTO `country` VALUES ('1', '1', 'US'), ('2', '2', 'US'), ('3', '3', 'AUT'), ('4', '4', 'DE'), ('5', '5', 'DE'), ('6', '6', 'CH');
COMMIT;
-- ----------------------------
-- Table structure for `region`
-- ----------------------------
DROP TABLE IF EXISTS `region`;
CREATE TABLE `region` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`usersId` int(11) NOT NULL,
`region` varchar(150) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of `region`
-- ----------------------------
BEGIN;
INSERT INTO `region` VALUES ('1', '1', '47798'), ('2', '2', '47798'), ('3', '3', '444'), ('4', '4', '78965'), ('5', '5', '7856'), ('6', '6', '7856');
COMMIT;
-- ----------------------------
-- Table structure for `search`
-- ----------------------------
DROP TABLE IF EXISTS `search`;
CREATE TABLE `search` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`country` varchar(100) NOT NULL,
`usersId` int(11) NOT NULL,
`region` varchar(100) NOT NULL,
`status` varchar(150) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of `search`
-- ----------------------------
BEGIN;
INSERT INTO `search` VALUES ('1', 'US', '1', '47798', 'Angestellter'), ('2', 'US', '2', '79653', 'Angestellter'), ('3', 'AUT', '3', '444', 'Chef'), ('4', 'DE', '4', '78965', 'Gesellschafter'), ('5', 'DE', '5', '7856', 'Vertrieb'), ('6', 'DE', '6', '47798', 'Angestellter');
COMMIT;
-- ----------------------------
-- Table structure for `status`
-- ----------------------------
DROP TABLE IF EXISTS `status`;
CREATE TABLE `status` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`usersId` int(11) NOT NULL,
`status` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of `status`
-- ----------------------------
BEGIN;
INSERT INTO `status` VALUES ('1', '1', 'Angestellter'), ('2', '2', 'Angestellter'), ('3', '3', 'Chef'), ('4', '4', 'Gesellschafter'), ('5', '5', 'Vertrieb'), ('6', '6', 'Vertrieb');
COMMIT;
-- ----------------------------
-- Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
-- ----------------------------
-- Records of `users`
-- ----------------------------
BEGIN;
INSERT INTO `users` VALUES ('1', 'Heinz'), ('2', 'Karl'), ('3', 'Helmut'), ('4', 'Viktor'), ('5', 'Thomas'), ('6', 'Kurt');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
And this is my Select, what not working correctly, i only geht the search-table entries:
select * from users
inner join region on users.id=region.usersid
inner join country on users.id=country.usersid
inner join status on users.id=status.usersid
where users.id in (select usersId from search where country = 'DE' AND region LIKE '7%');
You can use the following query (modified the select you were using in your question):
select * from users
inner join search
on search.usersid = users.id
where country = 'DE' AND region LIKE '7%'
You can change the where clause as per your requirement.
Also, it is a good practice to maintain consistency in nomenclature of the columns within different tables especially the primary keys/identity columns. For example: In your table definition, Id in users table but usersId in search table.

how to get vistors_sum and reviews_count in 3 table?

how to get vistors_sum and reviews_count in 3 table ?
see the bellow codes, how to get my result in one sql?
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `a`
-- ----------------------------
DROP TABLE IF EXISTS `a`;
CREATE TABLE `a` (
`products_id` int(11) NOT NULL,
`products_name` varchar(255) default NULL,
PRIMARY KEY (`products_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of a
-- ----------------------------
INSERT INTO `a` VALUES ('1', 'jimmy');
INSERT INTO `a` VALUES ('2', 'tina');
INSERT INTO `a` VALUES ('3', 'emma');
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `b`
-- ----------------------------
DROP TABLE IF EXISTS `b`;
CREATE TABLE `b` (
`id` int(11) NOT NULL auto_increment,
`products_id` int(11) NOT NULL,
`vistors` int(11) NOT NULL,
`date` date default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of b
-- ----------------------------
INSERT INTO `b` VALUES ('1', '1', '1', '2013-11-13');
INSERT INTO `b` VALUES ('2', '1', '2', '2013-11-04');
INSERT INTO `b` VALUES ('3', '2', '1', '2013-11-13');
INSERT INTO `b` VALUES ('4', '2', '3', '2013-11-13');
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `c`
-- ----------------------------
DROP TABLE IF EXISTS `c`;
CREATE TABLE `c` (
`id` int(11) NOT NULL auto_increment,
`products_id` int(11) NOT NULL,
`review_content` varchar(255) default NULL,
`date` date default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of c
-- ----------------------------
INSERT INTO `c` VALUES ('1', '1', 'hello', '2013-11-13');
INSERT INTO `c` VALUES ('2', '1', 'world', '2013-11-13');
INSERT INTO `c` VALUES ('3', '2', 'good', '2013-11-12');
INSERT INTO `c` VALUES ('4', '3', 'boy', '2013-11-13');
this code bellow can do but the date condition is in sub children temp table. this make the sql not flexible (if I want to query any time not 2013-11-13)
select
a.products_id,
a.products_name,
b.vistors_sum,
c.reviews_count
from
a
left join
(
select
b.products_id,
b.date,
sum(b.vistors) as vistors_sum
from b
where b.date = '2013-11-13'
group by b.products_id
) as b on a.products_id = b.products_id
left join
(
select
c.products_id,
count(c.products_id) as reviews_count
from c
where c.date = '2013-11-13'
group by c.products_id
) as c on a.products_id = c.products_id
SQLFiddle demo
select a.products_id,
products_name,
COALESCE(b.sum_visitors,0) as sum_visitors,
COALESCE(c.count_comments,0) as count_comments
from a
left join
( SELECT products_id,sum(vistors) as sum_visitors
FROM b
WHERE date='2013-11-13'
GROUP BY products_id
) as b
on (a.products_id=b.products_id)
left join
(
SELECT products_id,count(*) as count_comments
FROM c
WHERE date='2013-11-13'
GROUP BY products_id
) as c
on (a.products_id=c.products_id)

table structure for personal messages

What is the best table structure to store dialogs between users in private messages?
Each user can send personal message to many recepients.
Each message has flag for sender: is message deleted or not
Each message has flag for receiver: is message unread, read or deleted
Each message can be deleted (set flag 'deleted')
PrivateMessages' main page should look like this:
E.g. User1 sends Message1 to User2 and User3.
On private message page I have to show 2 same messages:
sent Message1 to user2
sent Message1 to user3
next step - User2 replies to Message2, I'll see on the same page following:
received Message2 from user2 (reply on Message1)
sent Message1 to user3
next step, I answer to message3, I'll see
sent Message3 to user2
sent Message1 to user3
and so on.
Can anyone provide a table-structure?
I'm using MySQL 5.5
Main question. How can I get only the last non-deleted message of each dialog?
UPD.
I need to see on main page dialog list, between current user and other users (with pagination, sorted by Date DESC).
I will answer your main question first, then show the table structure I will use for this.
To get only the last non-deleted message of a particular dialog:
select
Message.Id
,Message.Subject
,Message.Content
from Message
join Junc_Message_To on Fk_Message = Message.Id
where Junc_Message_To.Fk_User = {RECIPIENT_ID}
and Message.Fk_User__From = {SENDER_ID}
and Junc_Message_To.Deleted is null
order by Junc_Message_To.Sent desc
limit 1
A simple three table structure could be used.
Table 1 stores user records - one record per user.
Table 2 stores message record - one record per message, foreign key relates to the user that sent the message.
Table 3 stores the correlation between messages and users that have had the messages sent to them.
Here is the SQL that is used to create the above table diagram:
create table `User` (
`Id` int not null auto_increment ,
`Username` varchar(32) not null ,
`Password` varchar(32) not null ,
primary key (`Id`) ,
unique index `Username_UNIQUE` (`Username` ASC) )
engine = InnoDB
create table `Message` (
`Id` int not null auto_increment ,
`Fk_User__From` int not null ,
`Subject` varchar(256) not null ,
`Content` text not null ,
primary key (`Id`) ,
index `Fk_Message_User__From` (`Fk_User__From` ASC) ,
constraint `Fk_Message_User__From`
foreign key (`Fk_User__From` )
references `User` (`Id` )
on delete cascade
on update cascade)
engine = InnoDB
create table `Junc_Message_To` (
`Fk_Message` int not null ,
`Fk_User` int not null ,
`Sent` datetime not null ,
`Read` datetime not null ,
`Deleted` datetime not null ,
PRIMARY KEY (`Fk_Message`, `Fk_User`) ,
INDEX `Fk_Junc_Message_To__Message` (`Fk_Message` ASC) ,
INDEX `Fk_Junc_Message_To__User` (`Fk_User` ASC) ,
constraint `Fk_Junc_Message_To__Message`
foreign key (`Fk_Message` )
references `Message` (`Id` )
on delete cascade
on update cascade,
constraint `Fk_Junc_Message_To__User`
foreign key (`Fk_User` )
references `User` (`Id` )
on delete cascade
on update cascade)
engine = InnoDB
I've done this in the past with a MessageRecipient table that simply contains the MessageID, ReceiverID, and Status. I had FolderID in that table as well, but you don't have that requirement. The Message table did not store any information about the recipient at all.
It is a join to retrieve a users messages, but does prevent duplication of the message subject and body between recipients.
Here's my approach at this, based on the information you provided.
User table is a give in. Mine is just id and name.
We obviously need a table to store messages. We need to know who authored it, the subject, the message content, and (probably) when it was created/sent.
We need to know who the message_recipients are. Technically even the message.author is sent a copy of the message (in most cases), but it is usually put in a folder='Sent'. Everyone else probably got it in their folder="Inbox". User's could then move the message to their folder='Trash' or delete it completely. If for some reason you need to retain messages after the user has deleted them, you could do so by making a folder='Deleted' with a folder.type='System'. If not, just delete the record in the message_recipients table for that message_recipient.user.
So here is the info for that. See the test cases for querying after the schema and data.
Schema:
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` tinytext NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
CREATE TABLE `message` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`author` int(11) unsigned NOT NULL,
`subject` varchar(255) NOT NULL,
`message` mediumtext NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_m_author` (`author`),
CONSTRAINT `fk_m_author` FOREIGN KEY (`author`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `message_folder_type`;
CREATE TABLE `message_folder_type` (
`name` varchar(40) NOT NULL,
`type` enum('System','User') NOT NULL DEFAULT 'User',
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `message_recipient`;
CREATE TABLE `message_recipient` (
`message` int(11) unsigned NOT NULL,
`user` int(11) unsigned NOT NULL,
`folder` varchar(40) NOT NULL,
PRIMARY KEY (`message`,`user`),
KEY `fk_mr_user` (`user`),
KEY `fk_mr_message_folder` (`folder`),
CONSTRAINT `fk_mr_message_folder` FOREIGN KEY (`folder`) REFERENCES `message_folder_type` (`name`) ON UPDATE CASCADE,
CONSTRAINT `fk_mr_message` FOREIGN KEY (`message`) REFERENCES `message` (`id`) ON UPDATE CASCADE,
CONSTRAINT `fk_mr_user` FOREIGN KEY (`user`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Test data:
INSERT INTO `user` VALUES ('1', 'Bob');
INSERT INTO `user` VALUES ('2', 'Harry');
INSERT INTO `user` VALUES ('3', 'Salley');
INSERT INTO `user` VALUES ('4', 'Jim');
INSERT INTO `user` VALUES ('5', 'Jake');
INSERT INTO `user` VALUES ('6', 'Randall');
INSERT INTO `user` VALUES ('7', 'Ashley');
INSERT INTO `message` VALUES ('1', '4', 'Message 1', 'this is a message', '2011-03-01 15:47:07');
INSERT INTO `message` VALUES ('2', '2', 'Message 2', 'this is a reply to message 1', '2011-03-02 15:47:28');
INSERT INTO `message` VALUES ('3', '7', 'Message 3', 'another cool message', '2011-03-02 15:48:15');
INSERT INTO `message` VALUES ('4', '4', 'Message 4', 'blah blah blah Sally', '2011-03-09 15:48:43');
INSERT INTO `message_folder_type` VALUES ('Deleted', 'System');
INSERT INTO `message_folder_type` VALUES ('Inbox', 'User');
INSERT INTO `message_folder_type` VALUES ('Sent', 'User');
INSERT INTO `message_folder_type` VALUES ('Trash', 'User');
INSERT INTO `message_recipient` VALUES ('1', '1', 'Inbox');
INSERT INTO `message_recipient` VALUES ('1', '2', 'Inbox');
INSERT INTO `message_recipient` VALUES ('2', '4', 'Inbox');
INSERT INTO `message_recipient` VALUES ('2', '5', 'Inbox');
INSERT INTO `message_recipient` VALUES ('3', '5', 'Inbox');
INSERT INTO `message_recipient` VALUES ('1', '4', 'Sent');
INSERT INTO `message_recipient` VALUES ('2', '2', 'Sent');
INSERT INTO `message_recipient` VALUES ('3', '7', 'Sent');
INSERT INTO `message_recipient` VALUES ('4', '4', 'Sent');
INSERT INTO `message_recipient` VALUES ('1', '3', 'Trash');
INSERT INTO `message_recipient` VALUES ('4', '3', 'Trash');
Test Case: Get the last, non-deleted, message of each dialog
I'm not completely sure what this means, but I'll assume "in a given user's inbox" and "not in the System Deleted folder" as part of my query.
SELECT message.`subject`, message.message, message.`author`
FROM message_recipient
INNER JOIN message ON message.id = message_recipient.message
WHERE
message_recipient.user = 4
AND message_recipient.folder != 'Deleted'
ORDER BY message.created DESC
This gives, based on the test data provided, the following results:
Subject Message Author
Message 4 blah blah blah Sally 4
Message 2 this is a reply to message 1 2
Message 1 this is a message 4
If I was an architector of the DB, I'd make structure like this (approx.)
CREATE TABLE statuses(
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (id),
UNIQUE INDEX name (name)
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;
CREATE TABLE users(
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
PRIMARY KEY (id),
UNIQUE INDEX name (name)
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;
CREATE TABLE messages(
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
reply_to INT(11) UNSIGNED NOT NULL,
sender INT(11) UNSIGNED NOT NULL,
recipient INT(11) UNSIGNED NOT NULL,
subject VARCHAR(255) DEFAULT NULL,
message TEXT DEFAULT NULL,
`time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
INDEX FK_messages_messages_id (reply_to),
INDEX FK_messages_users_id_recipient (recipient),
INDEX FK_messages_users_id_sender (sender),
CONSTRAINT FK_messages_messages_id FOREIGN KEY (reply_to)
REFERENCES messages (id) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FK_messages_users_id_recipient FOREIGN KEY (recipient)
REFERENCES users (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT FK_messages_users_id_sender FOREIGN KEY (sender)
REFERENCES users (id) ON DELETE NO ACTION ON UPDATE NO ACTION
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;
CREATE TABLE messages_statuses(
message_id INT(11) UNSIGNED NOT NULL,
status_id INT(11) UNSIGNED NOT NULL,
PRIMARY KEY (message_id, status_id),
INDEX FK_messages_statuses_statuses_id (status_id),
CONSTRAINT FK_messages_statuses_messages_id FOREIGN KEY (message_id)
REFERENCES messages (id) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FK_messages_statuses_statuses_id FOREIGN KEY (status_id)
REFERENCES statuses (id) ON DELETE CASCADE ON UPDATE CASCADE
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;
I don't see anything hard here but if you'll got any questions - feel free to ask.
id* INT, sender_id INT, recipient_id INT, message TEXT,
flag_s_deleted = 0 TINYINT, flag_r_deleted = 0 TINYINT, flag_r_read = 0 TINYINT,
sent_datetime DATETIME
"How can I get only the last
non-deleted message of each dialog?"
here you are:
select * from (...) where
(sender_id = ID1 and recipient_id = ID2 and flag_s_deleted = 0)
or (sender_id = ID2 and recipient_id = ID1 and flag_r_deleted = 0)
order by sent_date desc LIMIT 1
last message between you (ID1) and other person (ID2)
create database testMessage
go
use testMessage
go
CREATE TABLE [user] (
userid int NOT NULL IDENTITY,
name nvarchar(200) NOT NULL,
PRIMARY KEY (userid)
)
go
CREATE TABLE [message] (
msg_id int NOT NULL IDENTITY,
userid int NOT NULL,
msgContent nvarchar(200) NOT NULL,
created datetime NOT NULL default getdate(),
PRIMARY KEY (msg_id)
)
go
ALTER TABLE [message]
ADD FOREIGN KEY (userid) REFERENCES [user](userid)
ON DELETE CASCADE
ON UPDATE CASCADE
go
CREATE TABLE message_folder_type (
message_folder_type_name varchar(40) NOT NULL,
[type] varchar(10) NOT NULL DEFAULT 'User',
PRIMARY KEY (message_folder_type_name)
)
go
CREATE TABLE message_recipient (
message_recipient int NOT NULL,
userid int NOT NULL,
message_folder_type_name varchar(40) NOT NULL,
PRIMARY KEY (message_recipient,userid)
)
go
ALTER TABLE message_recipient
ADD FOREIGN KEY (message_folder_type_name) REFERENCES message_folder_type(message_folder_type_name)
ON DELETE CASCADE
ON UPDATE CASCADE
ALTER TABLE message_recipient
ADD FOREIGN KEY (message_recipient) REFERENCES [message](msg_id)
ON DELETE CASCADE
ON UPDATE CASCADE
ALTER TABLE message_recipient
ADD FOREIGN KEY (userid) REFERENCES [user](userid)
INSERT INTO [user] VALUES ('Bob');
INSERT INTO [user] VALUES ('Harry');
INSERT INTO [user] VALUES ('Salley');
INSERT INTO [user] VALUES ('Jim');
INSERT INTO [user] VALUES ('Jake');
INSERT INTO [user] VALUES ('Randall');
INSERT INTO [user] VALUES ('Ashley');
INSERT INTO [message] VALUES ('4', 'this is a message', '2011-03-01 15:47:07');
INSERT INTO [message] VALUES ('2', 'this is a reply to message 1', '2011-03-02 15:47:28');
INSERT INTO [message] VALUES ('7', 'another cool message', '2011-03-02 15:48:15');
INSERT INTO [message] VALUES ('4', 'blah blah blah Sally', '2011-03-09 15:48:43');
INSERT INTO message_folder_type VALUES ('Deleted', 'System');
INSERT INTO message_folder_type VALUES ('Inbox', 'User');
INSERT INTO message_folder_type VALUES ('Sent', 'User');
INSERT INTO message_folder_type VALUES ('Trash', 'User');
INSERT INTO message_recipient VALUES ('1', '1', 'Inbox');
INSERT INTO message_recipient VALUES ('1', '2', 'Inbox');
INSERT INTO message_recipient VALUES ('2', '4', 'Inbox');
INSERT INTO message_recipient VALUES ('2', '5', 'Inbox');
INSERT INTO message_recipient VALUES ('3', '5', 'Inbox');
INSERT INTO message_recipient VALUES ('1', '4', 'Sent');
INSERT INTO message_recipient VALUES ('2', '2', 'Sent');
INSERT INTO message_recipient VALUES ('3', '7', 'Sent');
INSERT INTO message_recipient VALUES ('4', '4', 'Sent');
INSERT INTO message_recipient VALUES ('1', '3', 'Trash');
INSERT INTO message_recipient VALUES ('4', '3', 'Trash');
SELECT [message].msg_id, [message].msgContent
FROM message_recipient
INNER JOIN message ON [message].msg_id = message_recipient.message_recipient
WHERE
message_recipient.userid = 4
AND message_recipient.message_folder_type_name != 'Deleted'
ORDER BY message.created DESC
fast action for sqlserver

Mysql - Help me alter this query to apply AND logic instead of OR in searching?

First execute these tables and data dumps :-
CREATE TABLE IF NOT EXISTS `Tags` (
`id_tag` int(10) unsigned NOT NULL auto_increment,
`tag` varchar(255) default NULL,
PRIMARY KEY (`id_tag`),
UNIQUE KEY `tag` (`tag`),
KEY `id_tag` (`id_tag`),
KEY `tag_2` (`tag`),
KEY `tag_3` (`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ;
INSERT INTO `Tags` (`id_tag`, `tag`) VALUES
(1, 'key1'),
(2, 'key2');
CREATE TABLE IF NOT EXISTS `Tutors_Tag_Relations` (
`id_tag` int(10) unsigned NOT NULL default '0',
`id_tutor` int(10) default NULL,
KEY `Tutors_Tag_Relations` (`id_tag`),
KEY `id_tutor` (`id_tutor`),
KEY `id_tag` (`id_tag`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `Tutors_Tag_Relations` (`id_tag`, `id_tutor`) VALUES
(1, 1),
(2, 1);
The following query finds all the tutors from Tutors_Tag_Relations table which have reference to at least one of the terms "key1" or "key2".
SELECT td . *
FROM Tutors_Tag_Relations AS td
INNER JOIN Tags AS t ON t.id_tag = td.id_tag
WHERE t.tag LIKE "%key1%"
OR t.tag LIKE "%key2%"
Group by td.id_tutor
LIMIT 10
Please help me modify this query so that it returns all the tutors from Tutors_Tag_Relations table which have reference to both the terms "key1" and "key2" (AND logic instead of OR logic). Please suggest an optimized query considering huge number of data records (the query should NOT individually fetch two sets of tutors matching each keyword and then find the intersection).
Update
Taking the question to the next level. Please run the following fresh queries :-
===================================================================================
CREATE TABLE IF NOT EXISTS learning_packs_tag_relations (
id_tag int(10) unsigned NOT NULL DEFAULT '0',
id_tutor int(10) DEFAULT NULL,
id_lp int(10) unsigned DEFAULT NULL,
KEY Learning_Packs_Tag_Relations_FKIndex1 (id_tag),
KEY id_lp (id_lp),
KEY id_tag (id_tag)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS learning_packs (
id_lp int(10) unsigned NOT NULL AUTO_INCREMENT,
id_status int(10) unsigned NOT NULL DEFAULT '2',
id_author int(10) unsigned NOT NULL DEFAULT '0',
name varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (id_lp)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ;
CREATE TABLE IF NOT EXISTS tutors_tag_relations (
id_tag int(10) unsigned NOT NULL DEFAULT '0',
id_tutor int(10) DEFAULT NULL,
KEY Tutors_Tag_Relations (id_tag),
KEY id_tutor (id_tutor),
KEY id_tag (id_tag)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS users (
id_user int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL DEFAULT '',
surname varchar(155) NOT NULL DEFAULT '',
PRIMARY KEY (id_user)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=52 ;
CREATE TABLE IF NOT EXISTS tutor_details (
id_tutor int(10) NOT NULL AUTO_INCREMENT,
id_user int(10) NOT NULL,
PRIMARY KEY (id_tutor)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=60 ;
CREATE TABLE IF NOT EXISTS tags (
id_tag int(10) unsigned NOT NULL AUTO_INCREMENT,
tag varchar(255) DEFAULT NULL,
PRIMARY KEY (id_tag),
UNIQUE KEY tag (tag)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
ALTER TABLE learning_packs_tag_relations
ADD CONSTRAINT Learning_Packs_Tag_Relations_ibfk_1 FOREIGN KEY (id_tag) REFERENCES tags (id_tag) ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE learning_packs
ADD CONSTRAINT Learning_Packs_ibfk_2 FOREIGN KEY (id_author) REFERENCES users (id_user) ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE tutors_tag_relations
ADD CONSTRAINT Tutors_Tag_Relations_ibfk_1 FOREIGN KEY (id_tag) REFERENCES tags (id_tag) ON DELETE NO ACTION ON UPDATE NO ACTION;
INSERT INTO test.users (
id_user ,
name ,
surname
)
VALUES (
NULL , 'Vivian', 'Richards'
), (
NULL , 'Sachin', 'Tendulkar'
);
INSERT INTO test.users (
id_user ,
name ,
surname
)
VALUES (
NULL , 'Don', 'Bradman'
);
INSERT INTO test.tutor_details (
id_tutor ,
id_user
)
VALUES (
NULL , '52'
), (
NULL , '53'
);
INSERT INTO test.tutor_details (
id_tutor ,
id_user
)
VALUES (
NULL , '54'
);
INSERT INTO test.tags (
id_tag ,
tag
)
VALUES (
1 , 'Vivian'
), (
2 , 'Richards'
);
INSERT INTO test.tags (id_tag, tag) VALUES (3, 'Sachin'), (4, 'Tendulkar');
INSERT INTO test.tags (id_tag, tag) VALUES (5, 'Don'), (6, 'Bradman');
INSERT INTO test.learning_packs (id_lp, id_status, id_author, name) VALUES ('1', '1', '52', 'Cricket 1'), ('2', '2', '52', 'Cricket 2');
INSERT INTO test.tags (id_tag, tag) VALUES ('7', 'Cricket'), ('8', '1');
INSERT INTO test.tags (id_tag, tag) VALUES ('9', '2');
INSERT INTO test.learning_packs_tag_relations (id_tag, id_tutor, id_lp) VALUES ('7', '52', '1'), ('8', '52', '1');
INSERT INTO test.learning_packs_tag_relations (id_tag, id_tutor, id_lp) VALUES ('7', '52', '2'), ('9', '52', '2');
===================================================================================
About the new system -
- The system now has 4 more tables - tutors, Users (linked to tutor_details), learning_packs, learning_packs_tag_relations
- Tutors create packs - tag relations for tutors stored in tutors_tag_relations and those for packs stored in learning_packs_tag_relations.
Now I want to search learning_packs, with the same AND logic. Help me modify the following query so that searching pack name or tutor's name, surname results all active packs (either directly those packs or packs created by those tutors).
==================================================================================
select lp.*
from Learning_Packs AS lp
LEFT JOIN Learning_Packs_Tag_Relations AS lptagrels ON lp.id_lp = lptagrels.id_lp
LEFT JOIN Tutors_Tag_Relations as ttagrels ON lp.id_author = ttagrels.id_tutor
LEFT JOIN Tutor_Details AS td ON ttagrels.id_tutor = td.id_tutor
LEFT JOIN Users as u on td.id_user = u.id_user
JOIN Tags as t on (t.id_tag = lptagrels.id_tag) or (t.id_tag = ttagrels.id_tag)
where lp.id_status = 1 AND ( t.tag LIKE "%Vivian%" OR t.tag LIKE "%Richards%" )
group by lp.id_lp HAVING count(lp.id_lp) > 1 limit 0,20
As you can see, searching "Cricket 1" returns that pack but searching Vivian Richards does not return the same pack.
Please help
Pretty simple if using Group and Having. This should get what you are looking for.
SELECT id_tutor
FROM Tutors_Tag_Relations AS td
INNER JOIN Tags AS t ON t.id_tag = td.id_tag
WHERE t.tag LIKE "%key1%"
or t.tag LIKE "%key2%"
group by id_tutor
having count(id_tutor)>1

How do I best combine and optimize these two queries?

Here is my main query which pulls in thread information as one row, it lacks the # of votes and currently I'm pulling that in with a second query.
SELECT Group_concat(t.tag_name) AS `tags`,
`p`.`thread_id`,
`p`.`thread_name`,
`p`.`thread_description`,
`p`.`thread_owner_id`,
`p`.`thread_view_count`,
`p`.`thread_reply_count`,
`p`.`thread_comment_count`,
`p`.`thread_favorite_count`,
`p`.`thread_creation_date`,
`p`.`thread_type_id`,
`p`.`thread_edited_date`,
`u`.*,
`x`.*,
`t`.*
FROM `shoop_posts` AS `p`
INNER JOIN `shoop_users` AS `u`
ON u.user_id = p.thread_owner_id
LEFT JOIN `shoop_tags_map` AS `x`
ON x.thread_id = p.thread_id
LEFT JOIN `shoop_tags` AS `t`
ON t.tag_id = x.tag_id
WHERE (p.thread_id = '1')
GROUP BY `p`.`thread_id`
My second query which pulls in the # of votes per thread:
SELECT Sum(vote_value)
FROM shoop_votes
INNER JOIN shoop_vote_codes
ON shoop_votes.vote_type = shoop_vote_codes.vote_type
WHERE thread_id = 1
AND shoop_votes.vote_type = 3
OR shoop_votes.vote_type = 2
A vote type of 2 is an upvote, 3 is a downvote. Here's the schema if you need it, and some sample data:
CREATE TABLE `shoop_posts` (
`thread_id` int(11) unsigned NOT NULL auto_increment,
`thread_name` text,
`thread_description` text,
`thread_parent_id` int(11) default NULL,
`thread_owner_id` int(11) default NULL,
`thread_view_count` int(11) default NULL,
`thread_reply_count` int(11) default NULL,
`thread_comment_count` int(11) default NULL,
`thread_favorite_count` int(11) default NULL,
`thread_creation_date` timestamp NULL default NULL,
`thread_type_id` int(11) default NULL,
`thread_edited_date` timestamp NULL default NULL,
PRIMARY KEY (`thread_id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of shoop_posts
-- ----------------------------
INSERT INTO `shoop_posts` VALUES ('1', 'Shoop that', '\r\n<img class=\"image-shoop\" src=\"\">\r\n\r\n<p>test:<br>\r\n\r\n\r\n</p>', null, '2', '217', '0', '0', '0', '2010-01-10 02:06:25', '1', null);
-- ----------------------------
-- Table structure for `shoop_tags`
-- ----------------------------
CREATE TABLE `shoop_tags` (
`tag_id` int(11) NOT NULL auto_increment,
`tag_name` varchar(11) default NULL,
PRIMARY KEY (`tag_id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of shoop_tags
-- ----------------------------
INSERT INTO `shoop_tags` VALUES ('1', 'mma');
INSERT INTO `shoop_tags` VALUES ('2', 'strikeforce');
INSERT INTO `shoop_tags` VALUES ('3', 'ufc');
-- ----------------------------
-- Table structure for `shoop_tags_map`
-- ----------------------------
DROP TABLE IF EXISTS `shoop_tags_map`;
CREATE TABLE `shoop_tags_map` (
`map_id` int(11) NOT NULL auto_increment,
`tag_id` int(11) default NULL,
`thread_id` int(11) default NULL,
PRIMARY KEY (`map_id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of shoop_tags_map
-- ----------------------------
INSERT INTO `shoop_tags_map` VALUES ('1', '1', '1');
INSERT INTO `shoop_tags_map` VALUES ('2', '2', '2');
INSERT INTO `shoop_tags_map` VALUES ('3', '1', '2');
INSERT INTO `shoop_tags_map` VALUES ('4', '3', '1');
INSERT INTO `shoop_tags_map` VALUES ('5', '3', '2');
-- ----------------------------
-- Table structure for `shoop_vote_codes`
-- ----------------------------
CREATE TABLE `shoop_vote_codes` (
`vote_type` smallint(1) NOT NULL default '0',
`vote_value` smallint(2) default NULL,
PRIMARY KEY (`vote_type`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of shoop_vote_codes
-- ----------------------------
INSERT INTO `shoop_vote_codes` VALUES ('2', '1');
INSERT INTO `shoop_vote_codes` VALUES ('3', '-1');
-- ----------------------------
-- Table structure for `shoop_votes`
-- ----------------------------
DROP TABLE IF EXISTS `shoop_votes`;
CREATE TABLE `shoop_votes` (
`thread_id` int(11) NOT NULL default '0',
`user_id` int(11) NOT NULL default '0',
`vote_type` smallint(1) NOT NULL default '0',
PRIMARY KEY (`thread_id`,`user_id`,`vote_type`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of shoop_votes
-- ----------------------------
INSERT INTO `shoop_votes` VALUES ('1', '1', '2');
INSERT INTO `shoop_votes` VALUES ('1', '2', '2');
INSERT INTO `shoop_votes` VALUES ('1', '3', '3');
If I understand you correctly, just using a subquery will do what you're after:
SELECT Group_concat(t.tag_name) AS `tags`,
`p`.`thread_id`,
`p`.`thread_name`,
`p`.`thread_description`,
`p`.`thread_owner_id`,
`p`.`thread_view_count`,
`p`.`thread_reply_count`,
`p`.`thread_comment_count`,
`p`.`thread_favorite_count`,
`p`.`thread_creation_date`,
`p`.`thread_type_id`,
`p`.`thread_edited_date`,
`u`.*,
`x`.*,
`t`.*,
`v`.VoteTotal
FROM `shoop_posts` AS `p`
INNER JOIN `shoop_users` AS `u`
ON u.user_id = p.thread_owner_id
LEFT JOIN `shoop_tags_map` AS `x`
ON x.thread_id = p.thread_id
LEFT JOIN `shoop_tags` AS `t`
ON t.tag_id = x.tag_id
LEFT JOIN (SELECT thread_id, Sum(vote_value) as VoteTotal
FROM shoop_votes
INNER JOIN shoop_vote_codes
ON shoop_votes.vote_type = shoop_vote_codes.vote_type
WHERE shoop_votes.vote_type = 3
OR shoop_votes.vote_type = 2
GROUP BY thread_id) as `v`
ON p.thread_id = v.thread_id
WHERE (p.thread_id = '1')
GROUP BY `p`.`thread_id`
This will let you get all threads as well if you just leave off where last where p.thread_id clause.