I have post 3 Tables structure like this Course,Students,CourseAllot with Data here i need how to multiple row combine single row.How to show the based on the name concatenate and show them
Create Table Course
(
CourseId int Primary key Identity(1,1),
CourseName Varchar(50)
)
Insert into Course values('C#')
Insert into Course values('Asp.net')
Insert into Course values('Sqlserver')
Insert into Course values('MySql')
Create Table Students
(
StudentId int Primary key identity(1,1),
StudentName varchar(30)
)
Insert into Students values('John')
Insert into Students values('David')
Insert into Students values('Hendry')
Insert into Students values('Smith')
Insert into Students values('Watson')
Create Table CourseAllot
(
AllotId int Primary key identity(1,1),
CourseId int,
StudentId int
)
Insert into CourseAllot values (1,1)
Insert into CourseAllot values (1,1)
Insert into CourseAllot values (2,1)
Insert into CourseAllot values (1,2)
Insert into CourseAllot values (3,4)
Insert into CourseAllot values (3,5)
I need Output this
Sno Course Name Student Name
1 C# John,Hendry,David
2 Asp.net John
3 Sqlserver Smith,WatSon
if you are in sqlserver use bellow query
with cte(courseName,c)
as
(select courseName,c= studentname from CourseAllot
inner join Course on CourseAllot.CourseId=Course.CourseId
inner join Students on Students.StudentId=CourseAllot.StudentId
group by courseName,studentname
)
select ROW_NUMBER() over(order by courseName) as rowno, courseName,
stuff((select ','+c from cte t where t.courseName=t2.courseName
for xml path('')),1,1,'') as StudentName from cte t2 group by t2.courseName
Related
Student stores a list of student name and Friend stores relationship between students.
Create table Student (
id int NOT NULL AUTO_INCREMENT,
name varchar(35),
PRIMARY KEY (id)
);
insert into Student (name) values ('John');
insert into Student (name) values ('Kelly');
insert into Student (name) values ('Mary');
Create table Friend (
id_from int NOT NULL REFERENCES Student(id),
id_to int NOT NULL REFERENCES Student(id),
PRIMARY KEY (id_from, id_to)
);
insert into Friend (id_from,id_to) values (1, 3);
insert into Friend (id_from,id_to) values (1, 2);
insert into Friend (id_from,id_to) values (3, 2);
How can I query all friends of "John", for example, in MySql? The schema is here.
http://sqlfiddle.com/#!9/aeacd/1
I have created a query. In general you can join tables with itself using the relation table. What the query does is join Student with Friend with Student and then selects the entries with "John" as name in the joined table between Student.id and Friend.id_from.
The query looks like this:
SELECT *
FROM Student as s1
INNER JOIN Friend as f1 on s1.id = f1.id_from
INNER JOIN Student as s2 on s2.id = f1.id_to
WHERE s1.name = "John";
you can try it out here:
http://sqlfiddle.com/#!9/aeacd/15
create table Student (
St_ID int not null,
St_Name varchar (100),
St_tel int,
St_ADD varchar (100) not null,
St_city varchar (100)not null,
St_type varchar (20) not null,
St_nationality varchar (20) not null,
Dep_ID int,
C_ID int,
primary key (St_ID),
foreign key (Dep_ID) references Department(Dep_ID),
foreign key (C_ID) references Course(C_ID),
)
create table Course (
C_ID int not null,
C_Name varchar (30) not null,
C_Duration varchar (10) not null,
DegreeType varchar (20),
Dep_ID int,
primary key (C_ID),
foreign key (Dep_ID) references Department (Dep_ID),
)
insert into Course Values (4040,'Software Engineering','18months','HND',001)
insert into Course Values (1454,'Business IT','6months','Diploma',001)
insert into Course Values (1534,'Business management ','18months','HND',002)
insert into Course Values (1245,'Digital Media','6months','Diploma',001)
insert into Course Values (1243,'Business Development','10months','Diploma',001)
INSERT INTO Student VALUES (1212,'jerome jacobs',0774750407,'no 66/7 senananyake lane ','nawala','fulltime','HND','SL',001,4040);
INSERT INTO Student VALUES (1713,'john paul',0773435646,'no 77/9 alvatigala lane','colombo ','parttime','Diploma','SL',001,1454);
INSERT INTO Student VALUES (1614,'Angelo mathews',0773436777,'no 88 rose lane colombo ','colombo 2','fulltime','HND','SL',002,1534);
INSERT INTO Student VALUES (1514,'jean paul',0713556688,'no 100/1 4th lane nawala','nawala','fulltime','Diploma','SL',002,1245);
INSERT INTO Student VALUES (1316,'Mark francis',0755657665,'no 54 1st lane ','kotte','parttime','HND','SL',003,4040);
INSERT INTO Student VALUES (1117,'Kevin steffan',0757667687,'no 99/5 railway lane ','nugegoda','parttime','Diploma','SL',004,1243);
SELECT DISTINCT Student.St_ID,St_Name,St_tel,St_ADD,St_type,DegreeType,C_Name from Student,Course where Student.St_type='parttime' and Course.DegreeType='HND';
this is my query to get information from two tables but it repeat values how can i fix that im really curious about sql im a beginner sorry for the way i ask questions i will be reall great full if it is answered
You have to JOIN the tables using the common field:
SELECT DISTINCT Student.St_ID,St_Name,St_tel,St_ADD,St_type,DegreeType,C_Name
from Student JOIN
Course ON Student.C_ID =Course.C_ID
where Student.St_type='parttime' and Course.DegreeType='HND';
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
Read more about joins here.
You have to use MySql Join , if you need to understand it more : http://dev.mysql.com/doc/refman/5.0/en/join.html
You have to join the student and course tables together by specifying their common column (key). Instead of this:
from Student,Course
do this:
from Student
join Course on student.C_ID= Course.C_ID
If you don't connect the two tables properly you'll get the cartesian product set.
Click for Information JOIN
SELECT S.St_ID, St_Name, St_tel, St_ADD, St_type, DegreeType, C_Name
FROM Student s
INNER JOIN Course C ON S.C_ID = C.C_ID
WHERE S.St_type='parttime' and C.DegreeType='HND'
GROUP BY S.St_ID;
My first table has department name and number of phd's. My second table has the professor's name in particular departments. I need to pull the professors that are in the departments with less than 50 phd's.
CREATE TABLE Dept (
dname VARCHAR(100),
numphds INT
);
INSERT INTO Dept VALUES ( '"Chemical Engineering"', 32 );
INSERT INTO Dept VALUES ( '"Civil Engineering"', 88 );
INSERT INTO Dept VALUES ( '"Computer Sciences"', 47 );
CREATE TABLE Prof (
pname VARCHAR(100),
dname VARCHAR(100)
);
INSERT INTO Prof VALUES ( '"Brian, C."', '"Chemical Engineering"' );
INSERT INTO Prof VALUES ( '"Brown, S."', '"Civil Engineering"' );
INSERT INTO Prof VALUES ( '"Jones, J."', '"Computer Sciences"' );
SELECT dname, numphds FROM dept WHERE numphds <50;
/using the following SELECT statement is where I am lost and cannot seem to understand how to get the professor name within my results of the dname and numphds that are <50. I know I won't get the results by using the FROM DEPT statement. Any ideas/
Personally, I would give Dept a primary key and index column deptId and have this also on the Prof table. That way, there's no need to join on a text field.
CREATE TABLE Dept (
deptId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
dname VARCHAR(100),
numphds INT
);
INSERT INTO Dept VALUES ( 1, 'Chemical Engineering', 32 );
INSERT INTO Dept VALUES ( 2, 'Civil Engineering', 88 );
INSERT INTO Dept VALUES ( 3, 'Computer Sciences', 47 );
CREATE TABLE Prof (
pname VARCHAR(100),
dname VARCHAR(100),
deptId INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
INSERT INTO Prof VALUES ( 'Brian, C.', 'Chemical Engineering', 1);
INSERT INTO Prof VALUES ( 'Brown, S.', 'Civil Engineering', 2);
INSERT INTO Prof VALUES ( 'Jones, J.', 'Computer Sciences', 3);
Second, you do realise that your text field have apostrophes?
To select them, using this format, I would join using the query
SELECT dept.dname, dept.numphds, prof.pname FROM dept join `prof` on prof.deptId = dept.deptId WHERE dept.numphds <50;
Here is your SQLFiddle demo.
MY situation is like this:
I have two tables
TEACHERS and ABSENCES each of them has a column unitid
I want to select the unitid from TEACHERS Table and insert into ABSENCES table.
EDIT:
Can this be added into this query: ("insert into absences (student_id, date) values ('".$_GET['student_id']."','".date('Y-m-d H:i:s')."')");
?
try this
INSERT INTO ABSENCES(unitid) select unitid from TEACHERS
I tried to depict your scenario as below
Create Absence Table
create table absence (absence_id int not null auto_increment primary key,
`date` datetime, `subject` varchar(20),
unit_session varchar(20), unitid int);
Insert Data to Absence Table
insert into absence(`date`, `subject`, unit_session)
values(now(),'Math','first'),(now(),'Biology','second'),(now(),'Physics','third')
Create and insert data to Teachers table
create table teachers (username varchar(10), `password` varchar(10), unitid int);
insert into teachers values('abcdsed','fgdfgfdfgd',23),
('abcdced','fgdfgrtfgd',3),('harikas','fgdfgfdfgd',23);
At this point as you can see, Absence Table don't have any value for unitid column. it's NULL.
Create a temporary table as below
create temporary table temptest(id int not null auto_increment primary key,
unit_id int);
Insert unitid from Teachers to temporary table
insert into temptest(unit_id) select unitid from teachers
Now finally, update Absence table by joining with temporary table like below
UPDATE absence a
JOIN temptest b
ON a.absence_id = b.id
SET a.unitid = b.unit_id
I am trying to insert a new row and set the customer_id with max()+1. The reason for this is the table already has a auto_increatment on another column named id and the table will have multiple rows with the same customer_id.
With this:
INSERT INTO customers
( customer_id, firstname, surname )
VALUES
((SELECT MAX( customer_id ) FROM customers) +1, 'jim', 'sock')
...I keep getting the following error:
#1093 - You can't specify target table 'customers' for update in FROM clause
Also how would I stop 2 different customers being added at the same time and not having the same customer_id?
You can use the INSERT ... SELECT statement to get the MAX()+1 value and insert at the same time:
INSERT INTO
customers( customer_id, firstname, surname )
SELECT MAX( customer_id ) + 1, 'jim', 'sock' FROM customers;
Note: You need to drop the VALUES from your INSERT and make sure the SELECT selected fields match the INSERT declared fields.
Correct, you can not modify and select from the same table in the same query. You would have to perform the above in two separate queries.
The best way is to use a transaction but if your not using innodb tables then next best is locking the tables and then performing your queries. So:
Lock tables customers write;
$max = SELECT MAX( customer_id ) FROM customers;
Grab the max id and then perform the insert
INSERT INTO customers( customer_id, firstname, surname )
VALUES ($max+1 , 'jim', 'sock')
unlock tables;
Use alias name for the inner query like this
INSERT INTO customers
( customer_id, firstname, surname )
VALUES
((SELECT MAX( customer_id )+1 FROM customers cust), 'sharath', 'rock')
SELECT MAX(col) +1 is not safe -- it does not ensure that you aren't inserting more than one customer with the same customer_id value, regardless if selecting from the same table or any others. The proper way to ensure a unique integer value is assigned on insertion into your table in MySQL is to use AUTO_INCREMENT. The ANSI standard is to use sequences, but MySQL doesn't support them. An AUTO_INCREMENT column can only be defined in the CREATE TABLE statement:
CREATE TABLE `customers` (
`customer_id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(45) DEFAULT NULL,
`surname` varchar(45) DEFAULT NULL,
PRIMARY KEY (`customer_id`)
)
That said, this worked fine for me on 5.1.49:
CREATE TABLE `customers` (
`customer_id` int(11) NOT NULL DEFAULT '0',
`firstname` varchar(45) DEFAULT NULL,
`surname` varchar(45) DEFAULT NULL,
PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
INSERT INTO customers VALUES (1, 'a', 'b');
INSERT INTO customers
SELECT MAX(customer_id) + 1, 'jim', 'sock'
FROM CUSTOMERS;
insert into table1(id1) select (max(id1)+1) from table1;
Use table alias in subquery:
INSERT INTO customers
( customer_id, firstname, surname )
VALUES
((SELECT MAX( customer_id ) FROM customers C) +1, 'jim', 'sock')
None of the about answers works for my case. I got the answer from here, and my SQL is:
INSERT INTO product (id, catalog_id, status_id, name, measure_unit_id, description, create_time)
VALUES (
(SELECT id FROM (SELECT COALESCE(MAX(id),0)+1 AS id FROM product) AS temp),
(SELECT id FROM product_catalog WHERE name="AppSys1"),
(SELECT id FROM product_status WHERE name ="active"),
"prod_name_x",
(SELECT id FROM measure_unit WHERE name ="unit"),
"prod_description_y",
UNIX_TIMESTAMP(NOW())
)
Your sub-query is just incomplete, that's all. See the query below with my additions:
INSERT INTO customers ( customer_id, firstname, surname )
VALUES ((SELECT MAX( customer_id ) FROM customers) +1), 'jim', 'sock')
You can't do it in a single query, but you could do it within a transaction. Do the initial MAX() select and lock the table, then do the insert. The transaction ensures that nothing will interrupt the two queries, and the lock ensures that nothing else can try doing the same thing elsewhere at the same time.
We declare a variable 'a'
SET **#a** = (SELECT MAX( customer_id ) FROM customers) +1;
INSERT INTO customers
( customer_id, firstname, surname )
VALUES
(**#a**, 'jim', 'sock')
This is select come insert sequel.
I am trying to get serial_no maximum +1 value and its giving correct value.
SELECT MAX(serial_no)+1 into #var FROM sample.kettle;
Insert into kettle(serial_no,name,age,salary) values (#var,'aaa',23,2000);