MySQL table column description help needed - php

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(50) NOT NULL,
`status` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
)
Please explain me what is doing UNIQUE KEY 'username' (username') statement in the example above and why ('username') is written once again?

The UNIQUE_KEY line is creating a unique index called 'username' on the column 'username'. A unique index allows only a single record to have a specific value. This is useful on rows like usernames because it prevents two users from being created with the same username.
However, I think you would get an error if you ran this because you have not defined a column called username.
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(50) NOT NULL,
`status` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
)

This is simply the format MySQL's CREATE TABLE syntax expects. If you look at the syntax in detail, you'll see...
UNIQUE [INDEX|KEY]
[index_name] [index_type] (index_col_name,...)
[index_option] ...
In other words, you're using an index_name of "username" which uses the "username" field/column. This might seem odd, but if you were using a compound key, you'd might have a definition something like...
UNIQUE KEY duplicate_lock (user_email, user_name)
...so you'd have different index name and column portions of the definition.

Related

Foreign key constraint makes SELECT query return 0 rows

I've been given this database structure:
DROP TABLE IF EXISTS `account`;
CREATE TABLE IF NOT EXISTS `account` (
`accountType` varchar(120) NOT NULL,
PRIMARY KEY (`accountType`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `username`;
CREATE TABLE IF NOT EXISTS `username` (
`usernameID` int(11) NOT NULL AUTO_INCREMENT,
`password` varchar(200) NOT NULL,
`name` varchar(200) NOT NULL,
`phoneNr` int(15) NOT NULL,
`email` varchar(120) NOT NULL,
`accountType` varchar(120) NOT NULL,
PRIMARY KEY (`usernameID`),
KEY `accountType` (`accountType`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `username`
ADD CONSTRAINT `username_ibfk_1` FOREIGN KEY (`accountType`) REFERENCES `account` (`accountType`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
Now, I want to SELECT a user from the username table. In MySQL workbench I get the results I'm looking for with:
SELECT name FROM username;
However, when using a mysqli query in PHP i get num_rows => 0 in my result object, like this:
(The var_dump above the result object is the query I'm sending in)
It works if I remove the KEY from the username table, so I assume that's where the problem lies. How should I alter my SELECT query?
I believe name is a reserved word in MySQL. You may just need to escape it using the backtick character like so,
SELECT `name` FROM username;
See Keywords and Reserved Words.
For some reason it seems like InnoDB was the issue. As soon as I removed ENGINE=InnoDB from the username table, everything worked.

Why won't my foreign key create in MySQL?

I've tried many different ways to create table with a foreign key and trying to insert into phpMyAdmin. However, it just not working as I was expected.
Here are what I've so far:
CREATE TABLE user (
user_id BIGINT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_name VARCHAR(50) NOT NULL,
user_password VARCHAR(50) NOT NULL);
This works perfectly fine. However, if I try to add a table with a foreign key thus, it refuses to create:
CREATE TABLE article (
article_id INT(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
article_title VARCHAR(100) NOT NULL,
article_content VARCHAR(1000) NOT NULL,
user_id INT(10) NOT NULL,
FOREIGN KEY (user_id) REFERENCES user (user_id));
This would not work as expected and would not add the table to the MySQL database. I get this error:
Cannot add foreign key constraint
How can I fix it?
We discovered in the comments that if a primary key is defined thus:
user_id BIGINT(10) UNSIGNED
then a foreign key like this will not work, since it needs to match on signedness (and I think type too):
user_id INT(10) NOT NULL
This works fine:
user_id BIGINT(10) UNSIGNED NOT NULL
Here's a Fiddle to demonstrate it working.

Sql Insert into with duplicate key

Ok so, im still a beginner in databases. i have this code
$sql="INSERT INTO complaints_members(password, complaint) VALUES ('$mypassword','$submit') ON DUPLICATE KEY UPDATE complaint='$submit' ; ";
This simply updates my complaint in the existing entry. How can i insert a new entry with the same key, instead of updating the old one?
Im thinking of it like this.
1st entry is like
Password : 123
Complaint : abc
2nd would be like
Password : 123
Complaint : def
Im not very familiar with the terms of SQL, so i'm sorry in advance, and thanks for your time.
EDIT: This is how the tables are
You can't have duplicate primary keys in a database. This is intentional.
Instead, consider re-designing your database so that each complaint has a unique ID (AKA a Primary Key). You should set it as something like complaint_id or simply id, and make it a PK (Primary Key) and AI (Auto-Increment). That way, when you do inserts you won't have to worry about updating the same row.
One option is to make password and complaint a composite primary key
For future reference when someone asks for your table structure its better to post the text from SHOW CREATE TABLE table_name instead of an image from a visual editor.
That said the problem is that your primary key is the password field. You need to add primary keys to both tabled than can be uniquely identified and then you need to link them.
Your table structure should be more like this:
CREATE TABLE `register` (
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`number` INTEGER(255),
`address` varchar(255),
PRIMARY KEY (`id`),
-- I assume that email and username should always be unique here
UNIQUE KEY (`email`)
UNIQUE KEY (`username`)
);
CREATE TABLE `complaints_members`
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`complaint` VARCHAR(255),
`password` varchar(255),
`member_id` INTEGER UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
KEY (`member_id`),
CONSTRAINT `complaints_members_register` FOREIGN KEY (`member_id`) REFERENCES `register` (`id`) ON DELETE CASCADE
);
So now to create a new member complaint your SQL would look like
INSERT INTO complaints_members(member_id, password, complaint) VALUES (?, ?, ?)
And to get all complaints for a member:
SELECT c.*
FROM compalaints_members c
WHERE c.member_id = ?

Polymorphic Associations or something easier

This is my first post and I can't seem to find the answer anywhere....
I have a database that has multiple companies,each company has multiple locations.
I'm running into problems trying to define the contacts. Some contacts need to be global and available
at any location....some contacts only need to exist for one location. In the contact_info table below
we specify the visibility of the contact (company or location). However the location needs to choose its primary contact.
That leaves a FK from contact -> location and from location -> contact.
I know there is another table involved but I can't seem to conceptualize it.
CREATE TABLE `company_info` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`));
CREATE TABLE `location_info` (
`id` INT NOT NULL AUTO_INCREMENT,
`company_info` INT NOT NULL DEFAULT -1,
`name` VARCHAR(100) NOT NULL DEFAULT '',
`primary_contact_id` INT NOT NULL DEFAULT -1,
PRIMARY KEY(`id`),
UNIQUE KEY(`company_id`,`name`),
FOREIGN KEY (company_id) REFERENCES company_info(id)
FOREIGN KEY (primary_contact_id) REFERENCES contact_info(id));
CREATE TABLE `contact_info` (
`id` INT NOT NULL AUTO_INCREMENT,
`company_id` INT
`location_id` INT,
`type` ENUM('Company','Location') NOT NULL DEFAULT 'Company',
`first_name` VARCHAR(50) NOT NULL DEFAULT '',
`last_name` VARCHAR(50) NOT NULL DEFAULT '',
PRIMARY KEY(`id`),
UNIQUE KEY(`id`,`company_id`,`location_id`),
FOREIGN KEY (location_id) REFERENCES location_info(id),
FOREIGN KEY (company_id) REFERENCES company_info(id)
The most effective way would be splitting it up so that there's a table for your companies, a table with your users, and a table solely for the purpose of storing all connections (i.e. EntryID, UserID, CompanyID). This way you'll be able to easily load them afterwards.

problem with mysql query

i have a table called users
this what the table look like
CREATE TABLE `users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`password` varchar(60) NOT NULL,
`email` varchar(60) NOT NULL,
PRIMARY KEY (`id`)
)
and finally i have a table called friends,
this what the table look like
CREATE TABLE `friends` (
`friendship_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id1` bigint(20) unsigned NOT NULL,
`user_id2` bigint(20) unsigned NOT NULL,
`time_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`friendship_id`),
KEY `user_id1` (`user_id1`),
KEY `user_id2` (`user_id2`),
CONSTRAINT `friends_ibfk_1` FOREIGN KEY (`user_id1`) REFERENCES `users` (`id`),
CONSTRAINT `friends_ibfk_2` FOREIGN KEY (`user_id2`) REFERENCES `users` (`id`)
)
so basically if userA is following userB , then a row will be added to the friends table, with the attribute user_id1 is userA and user_id2 is userB.
im trying to write a mysql query for a searchbox. the user will enter a string and the query will crawl a list of users that include that string but the people that the user is following need to be displayed first.
so if we have 3 users
jack
jason
john
if the user Chris (who's following jason) enters in the searchbox the string 'ja', the query will crawl the list of users with the following order jason,jack. since jason is followed by chris.
from my understanding , i think it might a group by problem, i tried different queries but i couldnt get the needed results
do you guys have any idea ?
thanks a lot
You have to do a trick for sorting, so friendships get a 0 and non-friendships get a 1 in a temporary field and then we sort ascending for this field and as second we sort by username
SELECT x.username
FROM users x LEFT JOIN friends y ON x.id=y.user_id2 AND y.user_id1=$LOGGED_IN_USER
WHERE LOWER(x.username) LIKE 'ja%'
ORDER BY CASE WHEN y.user_id2 IS NULL THEN 1 ELSE 0 END,x.username
#thanks to scwagner for pointing me to extend JOIN-clause

Categories