PHP SQL Inner Join or Union - mysql

I want to select different fields from two different tables My users table and my address table as shown below:
my users table:
CREATE TABLE IF NOT EXISTS `users` (
`ID` int(3) NOT NULL AUTO_INCREMENT,
`AccountNumber` int(8) NOT NULL,
`FirstName` text NOT NULL,
`LastName` text NOT NULL,
`EmailAddress` varchar(200) NOT NULL,
`Password` varchar(200) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `AccountNumber` (`AccountNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `users` (`ID`, `AccountNumber`, `FirstName`, `LastName`, `EmailAddress`, `Password`) VALUES
(1, 123456, 'test', 'test', 'test#test.ac.uk', '$2y$10$/j9nTE5ugmyrWuV8VNWFxe5iHInqyaTwxt5wDaxyQwPUZTDDjqNKm');
my address table:
CREATE TABLE IF NOT EXISTS `address` (
`AddID` int(4) NOT NULL AUTO_INCREMENT,
`HouseNumber` int(11) NOT NULL,
`StreetName` varchar(200) NOT NULL,
`City` varchar(200) NOT NULL,
`Postcode` varchar(8) NOT NULL,
`AccountNumber` int(8) NOT NULL,
PRIMARY KEY (`AddID`),
KEY `AccountNumber` (`AccountNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `address` (`AddID`, `HouseNumber`, `StreetName`, `City`, `Postcode`, `AccountNumber`) VALUES
(1, 123, 'Some Road', 'someCity', 'b66', 123456);
ALTER TABLE `address`
ADD CONSTRAINT `address_ibfk_1` FOREIGN KEY (`AccountNumber`) REFERENCES `users` (`AccountNumber`);
Ive manage to use the following inner join successfully:
SELECT * FROM users INNER JOIN address ON users.AccountNumber=address.AccountNumber
However that also seems to retrieve the auto incremented ID's as well as the password field which i dont want.
I tried union but kept getting the error about different number of columns. How would i change my select statement to only retrieve the FirstName, LastName and EmailAddress from the users table and the HouseNumber, Street, City and Postcode from the address table based on the account number stored in both tables.
Any info will be appreciated
Thanks!

Try this u will get the result
SELECT FirstName,LastName,EmailAddress,HouseNumber,
Street, City, Postcode FROM users
INNER JOIN address ON users.AccountNumber=address.AccountNumber

instead of select *, just list out the columns youd like
SELECT u.FirstName,u.LastName,u.EmailAddress,a.HouseNumber,a.StreetName,a.City,a.Postcode
FROM users u
INNER JOIN address a
ON u.AccountNumber=a.AccountNumber
from there you can add a where statement if you want to limit it down to one AccountNumber:
SELECT u.FirstName,u.LastName,u.EmailAddress,a.HouseNumber,a.StreetName,a.City,a.Postcode
FROM users u
INNER JOIN address a
ON u.AccountNumber=a.AccountNumber
WHERE u.AccountNumber=12345

Related

Is there a way to use MySQL fulltext to search related tables?

I have a table called persons which contains data about, well, people. It also contains foreign keys to another table. I'd like to make a fulltext index that is able to search the related tables for full text.
Here is some sample data: (see http://sqlfiddle.com/#!9/036fc5/2)
CREATE TABLE IF NOT EXISTS `states` (
`id` char(2) NOT NULL,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `states` (`id`, `name`) VALUES
('NY', 'New York'),
('NJ', 'New Jersey'),
('CT', 'Connecticut'),
('PA', 'Pennsylvania');
CREATE TABLE IF NOT EXISTS `persons` (
`id` int auto_increment NOT NULL,
`first_name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`state_id` char(2) not null,
PRIMARY KEY (`id`),
FULLTEXT (first_name, last_name, state_id)
);
INSERT INTO `persons` (`first_name`, `last_name`, `state_id`) VALUES
('Arnold', 'Asher', 'NY'),
('Bert', 'Bertold', 'NJ'),
('Charlie', 'Chan', 'NJ'),
('Darrin', 'Darcy', 'CT');
So, I'd like to be able to search for persons from "Jersey", such as:
SELECT * FROM persons WHERE MATCH(first_name, last_name, state_id) AGAINST('Jersey');
But, of course, the text "Jersey" exists only in the states table and not in the persons table. Does it make sense to make a materialized/generated index? Is there a simpler way?
You need to put a separate full-text index on the states table, and join with that.
CREATE TABLE IF NOT EXISTS `states` (
`id` char(2) NOT NULL,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT (name)
);
CREATE TABLE IF NOT EXISTS `persons` (
`id` int auto_increment NOT NULL,
`first_name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`state_id` char(2) not null,
PRIMARY KEY (`id`),
FULLTEXT (first_name, last_name);
SELECT p.*
FROM persons p
JOIN states s ON s.id = p.state_id
WHERE MATCH(s.name) AGAINST ('Jersey')
UNION
SELECT *
FROM persons
WHERE MATCH(first_name, last_name) AGAINST ('Jersey')
In MySQL, no type of index spans multiple tables. Not fulltext indexes, not spatial indexes, not btree indexes, not hash indexes.
Every type of index you can define belongs to exactly one table, and can index only the values in that table.

How to do a Select in an insert MySQL

My question is how do i do a select of one attribute in my table.
I have the following table->
CREATE TABLE `Group` (
`group_id` varchar(10) NOT NULL,
`user_id` varchar(10) NOT NULL,
`group_creator` varchar(20) NOT NULL,
`group_name` varchar(50) NOT NULL,
`date_created` datetime DEFAULT NULL,
CONSTRAINT UC_Group UNIQUE (group_id,group_code,group_name)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `Group`
ADD PRIMARY KEY (`group_id`),
ADD KEY (`user_id`);
I would like to insert the user_id from another table called User. However it is not working.
My insert is as follows->
INSERT INTO `Group` (`group_id`, `user_id`, `group_creator`, `group_name`, `date_created`)
SET `group_id`=UUID(), `user_id`=(SELECT user_id FROM User WHERE username='TheDoctor'), `group_creator`='TheDoctor', `group_name`='HeroesUnited', `date_created`= CURRENT_TIMESTAMP();
Source
INSERT INTO Group
SELECT UUID(),user_id,'TheDoctor','HeroesUnited', CURRENT_TIMESTAMP()
FROM User
WHERE username='TheDoctor'

selecting multiple rows issue in mysql

I am beginner in sql.
I have two tables users and installments
CREATE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(20) NOT NULL,
`password` varchar(10) NOT NULL,
`father_name` varchar(20) NOT NULL,
`phone` varchar(20) NOT NULL,
`cnic` varchar(20) NOT NULL,
`email` varchar(100) NOT NULL,
`address` varchar(100) NOT NULL,
`introducer` varchar(100) NOT NULL,
`date` date DEFAULT NULL,
`reg_number` varchar(100) DEFAULT NULL,
`installment` int(100) NOT NULL,
`user_level` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `cnic` (`cnic`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
INSERT INTO `users` (`id`, `user_name`, `password`, `father_name`, `phone`, `cnic`, `email`, `address`, `introducer`, `date`, `reg_number`, `installment`, `user_level`) VALUES
(2, 'qaser', 'Qaser1', 'zamarrud', '0312546879', '37406-3140185-1', 'tariq_kareem#yahoo.com', 'street # 6', 'rizwan', '2014-08-20', 'E-002', 3000, 0);
and
CREATE `installments` (
`installment_id` int(11) NOT NULL AUTO_INCREMENT,
`month` date DEFAULT NULL,
`prv_arrear` int(100) NOT NULL,
`amount` int(100) NOT NULL,
`total` int(100) NOT NULL,
`receive` int(100) NOT NULL,
`arrear` int(100) NOT NULL,
`fk_users_id` int(11) NOT NULL,
PRIMARY KEY (`installment_id`),
KEY `fk_users_id` (`fk_users_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
INSERT INTO `installments` (`installment_id`, `month`, `prv_arrear`, `amount`, `total`, `receive`, `arrear`) VALUES
(2, '2014-08-20', 2000, 2500, 4500, 3000, 1500);
when I run the following query I get the first table's record correctly but the second table's record showing NULL values
SELECT * FROM users
LEFT JOIN installments
ON users.id=installments.installment_id
WHERE users.cnic='37406-3140185-1';
Is there anything missing in the above query or is there another way to get the record from both tables simultaneously
id user_name password father_name phone cnic email address introducer date reg_number installment user_level installment_id month prv_arrear amount total receive arrear fk_users_id
2 qaser Qaser1 zamarrud 0312546879 37406-3140185-1 tariq_kareem#yahoo.com street # 6 rizwan 2014-08-20 s-001 3000 0 NULL NULL NULL NULL NULL NULL NULL NULL
I am also using the following query to inserting the record for getting primary key value and insert into foreign key
INSERT INTO `installments`(`id`, `month`, `prv_arrear`, `amount`, `total`, `receive`, `arrear`, fk_users_id)
SELECT NULL,now(),1000,2500,3500,3000,500, id
FROM users
WHERE cnic = '37406-3140190-1'
please help me thanks in advance and sorry if there is something wrong in my question because I am new in sql.
I suspect the right join condition is on fk_users_id. So this might do what you want:
SELECT *
FROM users u LEFT JOIN
installments i
ON u.id = i.fk_users_id
WHERE u.cnic = '37406-3140185-1';

mysql foreign key insert

Using this two tables i'm trying to create a query to insert a new course, but i'm using a foreign key and I don't know how to pass that users(table) id into courses(table) id.
I'm trying to get something like this
I'm completely lost, on how to insert data into a table that contains a foreign key,
what i'm trying to do is:
first a person can register(user table)
2.Then the user will be available to add courses ( im using the foreign key to identify the courses for a specific user)
Users table
id | username |
---------------
1 | test |
Courses table
coursesid | coursesname | id(same id that in users table)
1 | courses test| 1
The Create Table commands are
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` char(64) COLLATE utf8_unicode_ci NOT NULL,
`salt` char(16) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
CREATE TABLE `course` (
`courseid` int(11) NOT NULL AUTO_INCREMENT,
`coursename` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`id` int(11) NOT NULL,
UNIQUE KEY (`courseid`)
FOREIGN KEY (od) REFERENCES users(id)
)
You can use subquery for find user id, e.g.:
insert into course
(courseid, coursename, id)
values
(1, 'test courses',
(SELECT id FROM users where username = 'test')
)
;
Of cause, if you know user id, you can insert directly this id:
insert into course
(courseid, coursename, id)
values
(1, 'test courses', 1)
;
Additional query for insert just last user id:
insert into course
(courseid, coursename, id)
values
(1, 'test courses',
(SELECT max(id) FROM users)
)
;

mysql join, need suggestion

I have created a MySQL table with a foreign key value. I want to use MySQL join to fetch foreign key value.
I have a table called employee and foreign key value sex, Sex table contain Male & Female.
this is my simple join query which is working:
SELECT * FROM sex JOIN employee ON employee.sex_id=sex.id
but i want to use join query here, but it seems I am missing some thing, Please complete this:
SELECT employee_id, first_name, last_name, sex_id FROM employee
And please tell me how i will insert to forigen key in single query for this table:
CREATE TABLE IF NOT EXISTS `employee` (
`employee_id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(20) NOT NULL,
`middle_name` varchar(20) DEFAULT NULL,
`last_name` varchar(20) NOT NULL,
`employee_employee_id` int(11) DEFAULT NULL,
`address_id` int(11) DEFAULT NULL,
`phone_id` int(11) DEFAULT NULL,
`dob` date DEFAULT NULL,
`maritial_id` int(11) NOT NULL,
`sex_id` int(11) NOT NULL,
PRIMARY KEY (`employee_id`),
KEY `fk_employee_employee` (`employee_employee_id`),
KEY `fk_employee_address1` (`address_id`),
KEY `fk_employee_phone1` (`phone_id`),
KEY `fk_employee_maritial1` (`maritial_id`),
KEY `fk_employee_sex1` (`sex_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
I have not good idea in MySQL
SELECT emp.employee_id, emp.first_name, emp.last_name, emp.sex_id, sx.sex_label
FROM employee AS emp
JOIN sex AS sx
ON emp.sex_id = sx.id
Where sex_label is a field name in sex table that would contain either Male or Female.
Try something like:
SELECT e.employee_id, e.first_name, e.last_name, s.id
FROM employee AS e
JOIN sex AS s
ON e.sex_id = s.id