Properly join users table when there is both createdBy and updatedBy - php

I have a table environments that has both a createdBy field, as well as an updatedBy field. These fields store a member ID.
There is also a table members which houses the ID and the username. Below are the queries to create the tables
CREATE TABLE `environments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`createdBy` varchar(45) DEFAULT NULL,
`createdDtTm` datetime DEFAULT NULL,
`updatedBy` varchar(45) DEFAULT NULL,
`updatedDtTm` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8$$
CREATE TABLE `members` (
`member_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`firstname` varchar(100) DEFAULT NULL,
`lastname` varchar(100) DEFAULT NULL,
`login` varchar(100) NOT NULL DEFAULT '',
`passwd` varchar(32) NOT NULL DEFAULT '',
PRIMARY KEY (`member_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8$$
I would like to write a query that displays all the environments, but instead of an ID showing, I'd the the user name to show. Since they can be different though, I'm not sure how to write the join statement. Ideas?

You need a double join. SOmething along the lines of
SELECT
environments.*,
creators.firstname AS cfirstname,
creators.lastname AS clastname,
updaters.firstname AS ufirstname,
updaters.lasstname AS ulastname
FROM
environments
INNER JOIN members AS creators ON environments.createdBy=creators.login
LEFT JOIN members AS updaters ON environments.updatedBy=updaters.login
WHERE -- whatever

Related

How to select from relational database?

I am starting to learn how databases work and I have always had all my data in one table. I am looking over an open-source project which I would like to create an interface for and the database structure is too complicated for me to understand.
I am sure it has a relational database structure (if I have learned properly). This is what the database structure looks like:
-- Table structure for table `databasechangelog`
--
CREATE TABLE IF NOT EXISTS `databasechangelog` (
`ID` varchar(255) NOT NULL,
`AUTHOR` varchar(255) NOT NULL,
`FILENAME` varchar(255) NOT NULL,
`DATEEXECUTED` datetime NOT NULL,
`ORDEREXECUTED` int(11) NOT NULL,
`EXECTYPE` varchar(10) NOT NULL,
`MD5SUM` varchar(35) DEFAULT NULL,
`DESCRIPTION` varchar(255) DEFAULT NULL,
`COMMENTS` varchar(255) DEFAULT NULL,
`TAG` varchar(255) DEFAULT NULL,
`LIQUIBASE` varchar(20) DEFAULT NULL,
`CONTEXTS` varchar(255) DEFAULT NULL,
`LABELS` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
-- Table structure for table `databasechangeloglock`
--
CREATE TABLE IF NOT EXISTS `databasechangeloglock` (
`ID` int(11) NOT NULL,
`LOCKED` bit(1) NOT NULL,
`LOCKGRANTED` datetime DEFAULT NULL,
`LOCKEDBY` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
-- Table structure for table `devices`
--
CREATE TABLE IF NOT EXISTS `devices` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`uniqueid` varchar(128) NOT NULL,
`status` varchar(128) DEFAULT NULL,
`lastupdate` timestamp NULL DEFAULT NULL,
`positionid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_device_uniqueid` (`uniqueid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
-- --------------------------------------------------------
-- Table structure for table `positions`
--
CREATE TABLE IF NOT EXISTS `positions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`protocol` varchar(128) DEFAULT NULL,
`deviceid` int(11) NOT NULL,
`servertime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`devicetime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`fixtime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`valid` bit(1) NOT NULL,
`latitude` double NOT NULL,
`longitude` double NOT NULL,
`altitude` float NOT NULL,
`speed` float NOT NULL,
`course` float NOT NULL,
`address` varchar(512) DEFAULT NULL,
`attributes` varchar(4096) NOT NULL,
PRIMARY KEY (`id`),
KEY `position_deviceid_fixtime` (`deviceid`,`fixtime`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=145 ;
-- --------------------------------------------------------
-- Table structure for table `server`
--
CREATE TABLE IF NOT EXISTS `server` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`registration` bit(1) NOT NULL DEFAULT b'1',
`latitude` double NOT NULL DEFAULT '0',
`longitude` double NOT NULL DEFAULT '0',
`zoom` int(11) NOT NULL DEFAULT '0',
`map` varchar(128) DEFAULT NULL,
`language` varchar(128) DEFAULT NULL,
`distanceunit` varchar(128) DEFAULT NULL,
`speedunit` varchar(128) DEFAULT NULL,
`bingkey` varchar(128) DEFAULT NULL,
`mapurl` varchar(128) DEFAULT NULL,
`readonly` bit(1) NOT NULL DEFAULT b'0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
-- --------------------------------------------------------
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`email` varchar(128) NOT NULL,
`hashedpassword` varchar(128) NOT NULL,
`salt` varchar(128) NOT NULL,
`readonly` bit(1) NOT NULL DEFAULT b'0',
`admin` bit(1) NOT NULL DEFAULT b'0',
`map` varchar(128) NOT NULL DEFAULT 'osm',
`language` varchar(128) NOT NULL DEFAULT 'en',
`distanceunit` varchar(128) NOT NULL DEFAULT 'km',
`speedunit` varchar(128) NOT NULL DEFAULT 'kmh',
`latitude` double NOT NULL DEFAULT '0',
`longitude` double NOT NULL DEFAULT '0',
`zoom` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_user_email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
-- --------------------------------------------------------
-- Table structure for table `user_device`
--
CREATE TABLE IF NOT EXISTS `user_device` (
`userid` int(11) NOT NULL,
`deviceid` int(11) NOT NULL,
KEY `fk_user_device_deviceid` (`deviceid`),
KEY `user_device_user_id` (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `positions`
--
ALTER TABLE `positions`
ADD CONSTRAINT `fk_position_deviceid` FOREIGN KEY (`deviceid`) REFERENCES `devices` (`id`) ON DELETE CASCADE;
--
-- Constraints for table `user_device`
--
ALTER TABLE `user_device`
ADD CONSTRAINT `fk_user_device_deviceid` FOREIGN KEY (`deviceid`) REFERENCES `devices` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `fk_user_device_userid` FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE CASCADE;
When a user registers, it adds an entry to the "users" table and the user gets an id.
Then when the user adds a device, the user_device table looks like this:
And the devices table looks like this:
This is a GPS tracking software, so each device then posts it's position in the "positions" table which looks like this:
So, if a user logs in, how do I query the positions table and get all info from all devices of that user? I am assuming I would need to join the tables but I don't know how to do that. Any help would be greatly appreciated.
Let's build it incrementally. First, what is the actual data you want?
query the positions table
Ok, start with that:
SELECT
*
FROM
positions
Now how do you want to further filter that data?
from all devices of that user
Ok, so we need to relate this table (positions) through devices and to the user. So ultimately we'll need a WHERE clause like this:
WHERE
userid = ?
But positions doesn't have a userid, so let's walk through joining some tables until we have one. positions does have a deviceid, so we can join that:
SELECT
*
FROM
positions
INNER JOIN devices
ON positions.deviceid = devices.id
We still don't have a userid, though. And devices itself doesn't reference anything to further help us. But there's a table which does reference devices, user_device. Let's join that:
SELECT
*
FROM
positions
INNER JOIN devices
ON positions.deviceid = devices.id
INNER JOIN user_device
ON devices.id = user_device.deviceid
You'll see that we're getting a lot of data now. But you'll also see that we're now getting a userid column, so we can finally add our WHERE clause:
SELECT
*
FROM
positions
INNER JOIN devices
ON positions.deviceid = devices.id
INNER JOIN user_device
ON devices.id = user_device.deviceid
WHERE
userid = ?
At this point we should be getting all of the unique positions from any device related to that user. You can get just the position data by replacing SELECT * with SELECT positions.*, or you can explicitly define which columns from which tables you want to select.
it would appear from your notes that you know when the user logs in which device he has. if this is correct, you should not need a join. Just do a select on the positions table where the positions.deviceid = the login device.

Check if conversation exists

I have two tables one for the conversations and one for the messages.
For conversations
TABLE `conversations` (
`ai` bigint(20) NOT NULL AUTO_INCREMENT,
`conv_id` varchar(100) NOT NULL,
`user_a` varchar(100) NOT NULL,
`user_b` varchar(100) NOT NULL,
PRIMARY KEY (`ai`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
For messages
TABLE `conv_msgs` (
`ai` bigint(20) NOT NULL AUTO_INCREMENT,
`conv_id` varchar(100) NOT NULL,
`from_id` varchar(100) NOT NULL,
`the_msg` longtext NOT NULL,
`sent_date` varchar(100) NOT NULL,
`sent_time` varchar(100) NOT NULL,
`read` int(11) NOT NULL,
`db_timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ai`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
So what I am currently looking to do and for some reason I can't figure this out is I need a query that when a user goes to create a conversation it checks to see if the conversation between user_a and user_b already exists. The current users could be either a or b. I guess thats where I am stumped. Any insight?

Querying SQL multiple tables

I have a sql database with the following tables
Book Table
CREATE TABLE IF NOT EXISTS `books` (
`book_id` varchar(8) NOT NULL DEFAULT '',
`book_title` varchar(100) DEFAULT NULL,
`author1` varchar(20) NOT NULL,
`author2` varchar(20) DEFAULT NULL,
`publisher` varchar(20) NOT NULL,
`pub_year` year(4) NOT NULL,
`mod_id` varchar(8) NOT NULL,
`courseID` varchar(8) NOT NULL,
PRIMARY KEY (`book_id`),
KEY `id` (`book_id`),
KEY `book_id` (`book_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Courses Table
CREATE TABLE IF NOT EXISTS `courses` (
`courseID` varchar(8) NOT NULL,
`course_title` varchar(255) CHARACTER SET ascii NOT NULL,
`Entry_Year` int(1) NOT NULL,
`Duration` int(1) NOT NULL,
PRIMARY KEY (`courseID`),
KEY `courseID` (`courseID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Modules Table
CREATE TABLE IF NOT EXISTS `modules` (
`mod_id` varchar(8) NOT NULL,
`mod_title` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
PRIMARY KEY (`mod_id`),
KEY `mod_title` (`mod_title`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Module Course Table
CREATE TABLE IF NOT EXISTS `mod_course` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`module` varchar(8) NOT NULL,
`course` varchar(8) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=31 ;
I would like to query the database to show all book details of a course. A course has many modules and modules have many books. I have tried the following query but I think there is a problem with my tables as well. (FYI 'BIT' is the id of a course that is in the module course table)
SELECT b.book_id, b.book_title, b.author1, b.author2, b.publisher, b.pub_year, b.mod_id, mc.course
FROM books b
JOIN mod_course mc
WHERE mc.course = 'BIT'
I have had a deeper look at this and offer the following suggestion which includes changes to the data model also. This solution will also allow you to have the same book used for several modules (if required in the future). Also note the new table mod_books
The full code for this (including the query) is below... hope its ok
CREATE TABLE IF NOT EXISTS books
(book_id varchar(8) NOT NULL DEFAULT '',
book_title varchar(100) DEFAULT NULL,
author1 varchar(20) NOT NULL,
author2 varchar(20) DEFAULT NULL,
publisher varchar(20) NOT NULL,
pub_year year(4) NOT NULL,
PRIMARY KEY (book_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS courses
(course_ID varchar(8) NOT NULL,
course_title varchar(255) CHARACTER SET ascii NOT NULL,
Entry_Year int(1) NOT NULL,
Duration int(1) NOT NULL,
PRIMARY KEY (course_ID)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS modules
(mod_id varchar(8) NOT NULL,
mod_title varchar(255) NOT NULL,
description varchar(255) NOT NULL,
PRIMARY KEY (mod_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS mod_books
(mod_id varchar(8) NOT NULL,
book_id varchar(8) NOT NULL,
PRIMARY KEY (mod_id,book_id),
FOREIGN KEY (mod_id) REFERENCES modules (mod_id),
FOREIGN KEY (book_id) REFERENCES books (book_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS mod_course
(ID int(11) NOT NULL AUTO_INCREMENT,
mod_id varchar(8) NOT NULL,
course_ID varchar(8) NOT NULL,
PRIMARY KEY (ID),
FOREIGN KEY (mod_id) REFERENCES modules (mod_id),
FOREIGN KEY (course_ID) REFERENCES courses (course_ID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=31 ;
and the query would be
SELECT b.*
FROM mod_course mc
INNER JOIN mod_books mb
ON mb.mod_id = mc.mod_id
INNER JOIN books b
ON b.book_id = mb.book_id
WHERE mc.course_id = 'BIT'
based on the stated relationship course->module->books, you should drop the courseid column from the books table. the modid that you have is all you need.
the problem with your query is the missing join condition.
below the JOIN mod_course mc line you should add
ON mc.module = b.mod_id
After the keyword Join it should be ON not WHERE
SELECT B.*, MC.COURSE
FROM MODULECOURSE AS MC
INNER JOIN COURSES AS C
ON C.COURSE_TITLE = MC.COURSE
INNER JOIN BOOKS AS B
ON B.COURSEID= C.COURSEID

How to accurately set up a foreign key scenario in MySQL to accomplish my addressbook

I have been making a database and learning along the way. I recently got into using InnoDB and using foreign keys to connect tables together.
But in all honestly I'm probably making my foreign keys blindly. What is the correct set and check list that I need to use when making a foreign key.
My understanding with foreign keys is that I have a Master Table, and any changes in my Master Table are reflected to any tables that hold a foreign key to a specific column in it.
So my current log-in system has a set up like this
users
=====
id PK
username
password
and my other tables look like this
contacts
========
id PK
user_id references `users`.`id`
group
name
address
groups
======
id PK
user_id
group_name
group_contacts
==============
id PK
group_id references `group`.`id`
contact_id references `contacts`.`id`
To my understanding these tables can be deleted when the Master Table is deleted using the ON DELETE CASCADE option correct?
My problem now is that I can't seem to make group_id and contact_id a Foreign key to groups.id and contacts.id with this setup. I get an error when running the SQL statements.
I'm trying to make my address book so that when a user places a contact into a group becomes all automated and I don't have to change much information. The group_contact table is what I THINK I will querying when I want to see where each contact belongs to. If I change the name of a group it will reflect across all tables right? This is where foreign keys come in and I'm confusing myself with how these keys should behave for me.
But like I said I can't seem to make a foreign key without getting an error.
I know I can Google my Foreign Key question, which I have but I can't seem to learn this way without getting feedback and input to my exact scenario ;(
Not to ask too much but because of my confusion I'm also having a hard time trying to see how I can make a PHP script to handle the group name change and query the database to pull down contacts that belong to a specific group.
This would really help me a lot guys, and I hope to learn something!
My query is this:
ALTER TABLE `list_`.`groups_contacts`
ADD CONSTRAINT `group_id` FOREIGN KEY (`group_id`) REFERENCES `list_`.`groups` (`id`)
ADD CONSTRAINT `contact_id` FOREIGN KEY (`contact_id`) REFERENCES `list_`.`contacts` (`id`);
My database looks like this:
CREATE TABLE `list_`.`buyer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL,
`isClosed` tinyint(1) NOT NULL,
`display_limit` int(1),
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`prop_address` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`state` varchar(11) NOT NULL,
`zip` varchar(5) NOT NULL,
`cell_phone` varchar(16) NOT NULL,
`home_phone` varchar(16) NOT NULL,
`other1` varchar(16) NOT NULL,
`other2` varchar(16) NOT NULL,
`comments` text NOT NULL,
`comment_exist` tinyint(1) NOT NULL,
`comment_date` text NOT NULL,
`date_added` date NOT NULL,
`date_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`,`user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 AUTO_INCREMENT=23 ;
CREATE TABLE `list_`.`company` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL DEFAULT '0',
`company_name` varchar(128) NOT NULL,
PRIMARY KEY (`id`, `user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
CREATE TABLE `list_`.`contacts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL,
`group` varchar(128) NOT NULL,
`first_name` varchar(128) NOT NULL,
`last_name` varchar(128) NOT NULL,
`address` varchar(128) NOT NULL,
`city` varchar(128) NOT NULL,
`state` varchar(2) NOT NULL,
`zip` int(5) NOT NULL,
`phone_number` varchar(16) NOT NULL,
`cell_number` varchar(16) NOT NULL,
`work_number` varchar(16) NOT NULL,
`fax_number` varchar(16) NOT NULL,
`email` varchar(128) NOT NULL,
`company` varchar(55) NOT NULL,
`title` varchar(56) NOT NULL,
`notes` text NOT NULL,
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`,`user_id`),
KEY `user_id` (`user_id`),
KEY `group` (`group`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;
CREATE TABLE `list_`.`groups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL,
`position` int(8) unsigned NOT NULL DEFAULT '0',
`name` varchar(128) NOT NULL,
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`,`user_id`),
KEY `user_id` (`user_id`),
KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8 AUTO_INCREMENT=32 ;
CREATE TABLE `list_`.`prospect` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL,
`isClosed` tinyint(1) DEFAULT '0',
`display_limit` int(1) DEFAULT '0',
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`prop_address` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`state` varchar(11) NOT NULL,
`zip` varchar(5) NOT NULL,
`cell_phone` varchar(16) NOT NULL,
`home_phone` varchar(16) NOT NULL,
`other1` varchar(16) NOT NULL,
`other2` varchar(16) NOT NULL,
`comments` text NOT NULL,
`date_added` date NOT NULL,
`date_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`,`user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
CREATE TABLE `list_`.`seller` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL,
`file` int(11) DEFAULT NULL,
`isClosed` tinyint(1) NOT NULL,
`display_limit` int(1) NOT NULL DEFAULT '0',
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`prop_address` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`state` varchar(22) NOT NULL,
`zip` varchar(5) NOT NULL,
`cell_phone` varchar(16) NOT NULL,
`home_phone` varchar(16) NOT NULL,
`other1` varchar(16) NOT NULL,
`other2` varchar(16) NOT NULL,
`comments` text NOT NULL,
`comment_exist` tinyint(1) NOT NULL,
`comment_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`date_added` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`date_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`,`user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ;
CREATE TABLE `list_`.`settings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` tinyint(11) NOT NULL,
`seller_display_limit` int(4) DEFAULT '0',
`buyer_display_limit` int(4) DEFAULT '0',
`prospect_display_limit` int(4) DEFAULT '0',
`property_display_limit` int(4) DEFAULT '0',
`date_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`,`user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
CREATE TABLE `list_`.`users` (
`id` tinyint(11) NOT NULL AUTO_INCREMENT,
`md5_id` varchar(200) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`user_level` tinyint(1) DEFAULT '1',
`first_name` varchar(200) NOT NULL,
`last_name` varchar(200) NOT NULL,
`email` varchar(200) DEFAULT NULL,
`approved` int(1) NOT NULL,
`banned` int(1) NOT NULL,
`date_joined` date NOT NULL,
`ip` varchar(15) DEFAULT NULL,
`activation_code` int(9) DEFAULT NULL,
`ckey` varchar(220) NOT NULL,
`ctime` varchar(220) NOT NULL,
`last_logged_in` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`account_number` varchar(128) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
ALTER TABLE `list_`.`buyer`
ADD CONSTRAINT `buyer_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE;
--
-- Constraints for table `company`
--
ALTER TABLE `list_`.`company`
ADD CONSTRAINT `company_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE;
--
-- Constraints for table `contacts`
--
ALTER TABLE `list_`.`contacts`
ADD CONSTRAINT `contacts_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
ADD CONSTRAINT `group_ibfk_2` FOREIGN KEY (`group`) REFERENCES `groups` (`name`) ON UPDATE CASCADE;
--
-- Constraints for table `groups`
--
ALTER TABLE `list_`.`groups`
ADD CONSTRAINT `group_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `prospect`
--
ALTER TABLE `list_`.`prospect`
ADD CONSTRAINT `prospect_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `seller`
--
ALTER TABLE `list_`.`seller`
ADD CONSTRAINT `seller_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `settings`
--
ALTER TABLE `list_`.`settings`
ADD CONSTRAINT `settings_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
I think you slightly misunderstood the concept of Foreign Keys. Changing the name of a group is not supposed to reflect on any other table, you just change your group-table.
Assuming you have this simple scenario, where one Contact can belong only to one Group:
Groups
id
group_name
Contacts
id
group_id -> Groups.id
first_name
...
Your Contacts do not have the information about the group_name. You just store the reference to your Groups.id.
If you want to query your contacts and the name of their group, you join those two tables:
Select c.first_name, g.group_name
From contacts c
Join groups g On ( g.id = c.group_id )
If you want to change the name of a group, you do a simple update:
Update groups
Set group_name = 'Your new group name'
Where id = 99 --# The id of the group to rename
This only changes your Groups table, without changing your Contacts.
Your Foreign Key on Contacts.group_id is there to ensure the referential integrity. This means, that you are not allowed to have a contact with group_id=88 if there is no record in Groups with id=88.
Using ON DELETE CASCADE would delete all Contacts that are members of a certain group, once you delete that group.

Unable to relate two MySQL tables (foreign keys)

Here is my USER table
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`expiry` varchar(6) NOT NULL,
`contact_id` int(11) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(100) NOT NULL,
`level` int(3) NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`,`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
And here is my contact_info table
CREATE TABLE IF NOT EXISTS `contact_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`email_address` varchar(255) NOT NULL,
`company_name` varchar(255) NOT NULL,
`license_number` varchar(255) NOT NULL,
`phone` varchar(30) NOT NULL,
`fax` varchar(30) NOT NULL,
`mobile` varchar(30) NOT NULL,
`category` varchar(100) NOT NULL,
`country` varchar(20) NOT NULL,
`state` varchar(20) NOT NULL,
`city` varchar(100) NOT NULL,
`postcode` varchar(50) NOT NULL,
PRIMARY KEY (`id`,`email_address`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
The system uses username to login users. I want to modify it in such a way that it uses email for login. But there is no email_address in users table.
I have added foreign key - email in user table(which is email_address in contact_info).
How should I query database?
No, no, no, no no. Seriously, no. Don't make me come over there :-)
You're breaking third normal form by storing the email address twice.
The relationship need only be a short one, that of id. Assuming you're not guaranteeing the IDs will be identical in the two tables (i.e., my users.id isn't necessarily equal to my contact_info.id), just add a ci_id to the users table to act as a foreign key to the contact_info table.
Then the query to get a user's username and email will be something like:
select u.username, ci.email
from users u, contact_info ci
where u.username = 'paxdiablo'
and u.ci_id = ci.id;

Categories