I want to crate a table Person in mysql which has the values: Name, ID, Password, some other information and a table called items which has the values of Item,price, stock so each Person would have its information and a table of items that is unique for this exact Person.
So it would look something like this.
+------+-------+-------+
| ID | Name | Pass |
+------+-------+-------+-+
| 1165 | Exc |Itm|Pr|St|
| | +---------+
+------+-------| Sc|20|1 |
+---------+
I would be interested if it could be done in MYSQL, if it's not possible, what is possible for my situation.
Two tables, with a foreign key constraint.
As a simplistic example, the person table
CREATE TABLE person
( id INT NOT NULL PRIMARY KEY COMMENT 'PK'
, name VARCHAR(30)
) ENGINE=InnoDB
;
and the item table
CREATE TABLE item
( id INT NOT NULL PRIMARY KEY COMMENT 'PK'
, person_id INT NOT NULL COMMENT 'FK ref person.id'
, item VARCHAR(30)
, price DECIMAL(20,2)
, stock DECIMAL(18,0)
, CONSTRAINT FK_item_person FOREIGN KEY (person_id)
REFERENCES person (id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB
This implements a one-to-many relationship. A person can have zero, one or more item. An item belongs to exactly one person.
INSERT INTO person (id, name) VALUES
(1165,'Exc')
, (1066,'Foo')
;
INSERT INTO item (id, person_id, item, price, stock) VALUES
( 42, 1165, 'Sc', 20, 1 )
, ( 43, 1066, 'Ba', 12, 11 )
, ( 44, 1066, 'Co', 3, 2 )
;
CREATE TABLE Person (
ID int,
Name varchar(100),
Pass varchar(100),
PRIMARY KEY ID);
CREATE TABLE Item(
ID int,
Item varchar(100),
Price varchar(100),
Stock varchar(100),
FOREIGN KEY (ID) REFERENCES Person(ID)
);
those create 2 different tables.
This selects all and joins them.
Select * from Persons p
inner join Item i on p.ID = i.ID
Related
I would like to get tokens based on one WHERE condition. E.g if i would like to SELECT Gregor and if we look into committee it should retrive then the token for Liza, Matt
Table structure:
CREATE TABLE users(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255)
);
INSERT INTO users (name)
VALUES ("Gregor"),
("Liza"),
("Matt"),
("Bob");
CREATE TABLE committee(
user_id INT,
friend_id INT,
member_id INT,
PRIMARY KEY (`user_id`, `friend_id`, `member_id`),
FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
FOREIGN KEY (`friend_id`) REFERENCES `users` (`id`),
FOREIGN KEY (`member_id`) REFERENCES `users` (`id`)
);
INSERT INTO committee (user_id, friend_id, member_id)
VALUES (1, 2, 3),
(1, 2, 4);
CREATE TABLE tokens(
user_id INT,
token VARCHAR(255)
);
INSERT INTO tokens (user_id, token)
VALUES (1, "lclasld2"),
(2, "xxkakdasd"),
(3, "123kdkfs"),
(4, "hjj32");
Current query i got:
SELECT token FROM tokens WHERE user_id = 1;
How it behave now:
user_id, token
1, lclasld2
What i expect, when i run the query:
user_id, token
2, xxkakdasd
3, 123kdkfs
4, hjj32
You can union the select friend _id and member_id for user_id 1
SELECT
user_id, token
FROM tokens
WHERE user_id IN (SELECT friend_id FROM committee WHERE user_id = 1
UNION SELECT member_id FROM committee WHERE user_id = 1)
user_id | token
------: | :--------
2 | xxkakdasd
3 | 123kdkfs
4 | hjj32
db<>fiddle here
Instead of trying to insert all of values in one line, trying adding an insert for each individual object like so: INSERT INTO TOKENS() VALUES(); INSERT INTO TOKENS() VALUES(), so on and so forth.
I have three tables:
STUDENT table:
create table student
(
sid int auto_increment primary key,
fname varchar(30),
lname varchar(30)
);
COURSE table:
create table course
(
cid int auto_increment primary key,
ctype text,
cclass text,
cduration int,
certification int,
cteacher text,
standard_course_fee int,
);
STUDENT_PAYMENT table:
create table student_payment
(
transaction_id int auto_increment primary key,
sid int,
cid int,
paidamount int,
paiddate date,
paymentdue int,
FOREIGN KEY (sid) REFERENCES student(sid),
FOREIGN KEY (cid) REFERENCES course(cid)
);
I wrote this query:
select
sid, fname, lname, cid, ctype, cclass, paidamount, paiddate, paymentdue
from
student, student_payment, course
where
course.cid = student_payment.cid and
student.sid = student_payment.sid and
sid = 1;
To get expect output table like this:
|sid| fname | lname | ctype | cclass | paidamount | paiddate | paymentdue |
---------------------------------------------------------------------------
but I get an error:
Column sid in field list is ambiguous
Please someone correct my query.
You need to add alise as below. Also, use the join instead of adding all the tables in FROM
select student.sid,fname,lname,course.cid,ctype,cclass,paidamount,paiddate,paymentdue
from student
inner join student_payment on student.sid=student_payment.sid
inner join course on course.cid=student_payment.cid
where student.sid=1;
I'm new here in the community and I need your help in MySQL.
We have 3 Tables as follows:
student
lectures
student_visits_lectures(N:M Relationship)
student=({id},name,{id})
lectures=({lid},title{lid})
student_visits_lectures=({student,lectures})
What is the query for?:
List all students which visit all lectures.
For example:
We have students
We have 3 lectures(Math,English,Sport)
Now I want all students which visit all lectures.
Sorry for my broken English and formatting. I'll do my best in the future, but this is very important for me.
Thanks in advance!
Greetings
first add student's id and lectures's into student_visits_lectures table as foreign keys.
then write query as : select student from student_visits_lectures where sbl.student_id = student.id.
This is my current query:
SELECT name FROM student INNER JOIN student_visits_lectures ON student.id=student_visits_lectures.id INNER JOIN lectures ON student_visits_lectures.lid= lectures.lid
I did it guys. Thank you for all quick replying.
This is the solution:
We have 3 tables:
student
id | name
----------
1 | Jack
2 | Rick
lectures
lid | title
----------
1 | Math
2 | English
3 | Sport
student_visiting_lectures
sid |vlid
---------
1 | 1
1 | 2
1 | 3
2 | 2
3 | 3
Creating the table and inserting values
CREATE TABLE student(
id INT NOT NULL,
name VARCHAR(30),
PRIMARY KEY(id)
)ENGINE= InnoDB;
CREATE TABLE lectures(
lid INT NOT NULL,
title VARCHAR(40),
PRIMARY KEY(lid)
)ENGINE = InnoDB;
CREATE TABLE svl(
sid INT NOT NULL,
vlid INT NOT NULL,
PRIMARY KEY(sid,vlid),
FOREIGN KEY (sid) REFERENCES student(id),
FOREIGN KEY (vlid) REFERENCES lectures(lid)
) ENGINE = InnoDB;
INSERT INTO student VALUES(
1,'Jack'),
(2,'Rick');
INSERT INTO lectures VALUES(
1,'Math'),
(2,'English'),
(3,'Sport');
INSERT INTO svl VALUES(
1,1),
(1,2),
(1,3),
(2,1);
And this is the query
SELECT name, title FROM student
INNER JOIN svl ON id = sid
INNER JOIN lectures ON sid = vlid;
Since you want all students that have done all lectures, you can count how many lectures there are:
SELECT COUNT(*) as n FROM lectures;
Then, per student you can count how many lectures they follow:
SELECT student_id, COUNT(*) as n
FROM student_visits_lectures
GROUP BY student_id;
And you can filter the students that have followed all lectures:
SELECT s.*
FROM student_visits_lectures AS ls LEFT JOIN student AS s ON s.id=ls.student_id
GROUP BY student_id
HAVING COUNT(DISTINCT lecture_id) = (SELECT COUNT(*) FROM lectures);
See the fiddle.
This are the tables I have used:
CREATE TABLE student (
id INT NOT NULL,
name VARCHAR(64),
PRIMARY KEY (id)
);
CREATE TABLE lectures (
id INT NOT NULL,
title VARCHAR(100),
PRIMARY KEY(id)
);
CREATE TABLE student_visits_lectures (
student_id INT NOT NULL,
lecture_id INT NOT NULL
);
MySQL version 5.5.49, on Linux Mint (Ubuntu 14.04.1 based)
The people table contains all of a family: Jed, David, Sarah, and Luke. The cars table contains the two cars we own. The CarPeople table contains an entry for each person who rides in a car, and contains keys that associate the personID to the carID. Last is the carData table, which contains the color of a car, a personID of someone who last painted the car, an image of the paint job, a date of the paint job, and a url to see the image.
This is a strange example, but the idea is that only people who are associated with specific car id's can paint or ride in the car. The example data I inserted has Jed (1) and David (2) riding together in car 1, while David (2), Luke (3), and Sarah (4) ride in car 2.
The following query result must be contained in a view, where a parameter is passed in which references the personID:
Show the CarID, ImageURL, and all people that ride with the PersonID, but only for the latest DataEntryTime for each CarID.
My people_concat column isn't outputting correct results, but I can fix that later.
My main issue is I can't figure out how to output the data row for the max dataentrytime for each carid within this view. Changes I have tried result in only one row being outputted, I can't figure out how to do this.
The crucial test query is this:
select c.* from (select #p1:=2 p) parm , carRiderList c;
This does a select from the view with respect to user 2, David. Instead of 5 rows, only two should be outputted, the first of CarID 2, and the first of carID 1.
Running these queries should result in one row, the one containg the highest dataentrytime for the associated personID's:
select c.* from (select #p1:=1 p) parm , carRiderList c;
select c.* from (select #p1:=3 p) parm , carRiderList c;
select c.* from (select #p1:=4 p) parm , carRiderList c;
Thank you!(SQL Code is below)
/* People in the database */
create table People
(
PersonID int(11) not null unique auto_increment,
phoneNumber varchar(30) not null unique,
Name varchar(40) not null unique,
PRIMARY KEY (PersonID)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into People (phoneNumber, Name)
values ("123-456-7891", "Jed"), ("223-456-7891", "David"), ("323-456-7891", "Luke"), ("423-456-7891", "Sarah");
select * from People;
/* Cars */
drop table if exists Cars;
create table Cars
(
CarID int(11) not null unique auto_increment,
PurchaseTime date,
PRIMARY KEY (CarID)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into Cars (PurchaseTime)
values ("2016-1-1"),("2016-1-2");
select * from Cars;
/* CarPerson: Will contain an entry for each person who rides in the car, and can paint it */
drop table if exists CarPerson;
create table CarPerson
(
CarPersonID int(11) not null unique auto_increment,
CarID int(11) not null,
CarRiderID int(11) not null,
PRIMARY KEY (CarPersonID),
FOREIGN KEY (CarID) references Cars(CarID),
FOREIGN KEY (CarRiderID) references People(PersonID)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into CarPerson(CarID, CarRiderID)
values (1, 1), (1, 2), (2, 2), (2, 3), (2, 4);
select * from CarPerson;
/* CarData: Contains CarID, the color was that car was painted, and the person who painted it, as well as a (fake) imageurl */
create table carData
(
DataID int(11) not null unique auto_increment,
CarID int(11) not null,
Color varchar(20),
DataEntryTime date,
PainterID int(11) not null,
ImageURL varchar(255),
PRIMARY KEY (DataID),
FOREIGN KEY (CarID) references Cars(CarID),
FOREIGN KEY (PainterID) references People(PersonID)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into carData(CarID, Color, DataEntryTime, PainterID, ImageURL)
values (1, "Blue", "2013-1-1", 1, "http://www.bluecivic.com"),
(1, "Green", "2013-1-2", 3, "http://greencivic.com"),
(2, "Red", "2014-1-3", 4, "http://redford.com"),
(2, "Purple", "2014-1-4", 2, "http://purpleford.com"),
(2, "Black","2014-1-5", 3, "http://blackford.com");
select * from carData;
/* View I am having trouble with */
create function p1() returns INTEGER DETERMINISTIC NO SQL return #p1;
drop view carRiderList;
create view carRiderList as
(select distinct cp.CarID, cd.ImageURL, DataEntryTime, (
select group_concat(Name order by CarID, PersonID = p1())from People p
left join CarPerson cp
on p.PersonID = cp.CarPersonID
where cp.CarID IN (
select distinct(CarID)
from CarPerson cp
where cp.CarPersonID = p1()
limit 1
)
)
as people_concat
from CarPerson cp
left join carData cd
on cd.CarID = cp.CarID
where cp.CarRiderID = p1()) order by DataEntryTime desc;
select c.* from (select #p1:=2 p) parm , carRiderList c;
I want to write a sql script, which inserts into table some value for all the ids in some other table.
create table person
(
id int(11) not null auto_increment,
name varchar(255),
primary key (id)
);
insert into person
values (null, 'John'), (null, 'Sam');
select * from person;
id | name
----------
1 | John
2 | Sam
create table phone_details
(
id int(11) not null auto_increment,
person_id int(11),
phone int(11),
constraint person_ibfk_1 foreign key (person_id) references person (id) on delete no action,
primary key (id)
);
Now, in the phone_details table, I want the following :
id | person_id | phone
----------------------------
1 | 1 | 9999999999
2 | 2 | 9999999999
How do I do that ? Currently, I am using Java to write this one time script, but I think there must be a way of doing this in sql.
You can use INSERT INTO ... SELECT syntax:
INSERT INTO phone_details(person_id,phone)
SELECT id, 99999999
FROM person;
Consider storing phone number as VARCHAR.
SqlFiddleDemo