Fetching data from two tables? [duplicate] - mysql

This question already has an answer here:
how to fetch data from two tables in mysql?
(1 answer)
Closed 8 years ago.
I have to find out the output as name of student with highest marks? My both tables are-
CREATE TABLE student(Fields_ID INT, Name VARCHAR(20));
INSERT INTO student(Fields_ID,Name) VALUES(30,'JYOTI');
INSERT INTO student(Fields_ID,Name) VALUES(31,'KIRTI');
INSERT INTO student(Fields_ID,Name) VALUES(32,'YOGITA');
INSERT INTO student(Fields_ID,Name) VALUES(33,'RASHMI');
INSERT INTO student(Fields_ID,Name) VALUES(34,'NUPUR');
SELECT * FROM student;
CREATE TABLE Marks(Fields_ID INT, Student_ID INT NOT NULL,marks INT NOT NULL);
INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (30,40,100);
INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (31,41,88);
INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (32,42,72);
INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (33,43,33);
INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (34,44,15);
SELECT * FROM Marks;
I was trying to return the required out from the following code but it does not return same. Any idea why it is not returning the right values.I am a beginner in MySql so I am unable to find out the problem.
SELECT student.name,Marks.marks
FROM student INNER JOIN Marks
ON student.Fields_ID=Marks.Fields_ID;

SELECT student.name,Marks.marks
FROM student INNER JOIN Marks
ON student.Fields_ID=Marks.Fields_ID
where Marks.marks = (select max(marks) from Marks);

SELECT student.name,Marks.marks
FROM student
INNER JOIN Marks
ON student.Fields_ID=Marks.Student_ID
ORDER BY Marks.marks DESC
LIMIT 1

SELECT student.name,Marks.marks
FROM student INNER JOIN Marks
ON student.Fields_ID=Marks.Fields_ID
ORDER by marks DESC;
http://sqlfiddle.com/#!2/a5324/11
This is desired output?
EDIT: add LIMIT 1 to query if you want JUST ONE result.

Related

MySQL insert into table with values and where [duplicate]

This question already has answers here:
MySQL: Insert record if not exists in table [duplicate]
(16 answers)
Closed 7 years ago.
I have two tables event and guest and an eventGuest table that joins them together and has some information about the guest (like if they attended etc) and am trying to insert into the eventGuest table without creating a duplicate sort of like:
insert into eventGuest(eventID, GuestID, attended)
values(iEventID, iGuestID, bAttended)
where (select count(*) from eventGuest where eventID = iEventID and guestID = iGuestID) = 0
Copy one table data to another :-
INSERT INTO TARGET_TABLE (`col1`,`col2`) SELECT `col1`,`col2` FROM SOURCE_TABLE;
You should use INSERT INTO ... SELECT if you want to insert values from a table into another:
INSERT INTO eventGuest(eventID, GuestID, attended)
SELECT iEventID, iGuestID, bAttended
FROM Anothertable t
where NOT EXIST(select 1
from eventGuest e
where e.eventID = t.iEventID
and e.guestID = t.iGuestID);
Or, if you want to insert into the same table if the values of eventid and iGuestid doesn't exist, you can do this:
INSERT INTO eventGuest(eventID, GuestID, attended)
SELECT *
FROM ( SELECT 'eventid', 'guestid', 'somevalue' ) AS t
WHERE NOT EXISTS (
SELECT 1 FROM eventGuest e
WHERE e.eventID ='eventid'
and e.guestID = 'guestid'
) LIMIT 1;
Please do add a unique constraint in the eventGuest table for both eventid and guestid and use INSERT IGNORE or REPLACE command to insert the new data.

SQL Compare rows

Okay here is the situation:
I the following data in a table.
PAIR_NO NO NO2
3 5678EFGH 1234ABCD
4 1111BBBB 0000AAAA
1 1234ABCD 5678EFGH
2 0000AAAA 1111BBBB
The constraints are if no = no2 in another row skip that row.
So in this sample data the only rows that would be selected should be pair no 3 and 4.
I have tried to merge and inner join with self but I just keep getting all 4 rows back.
I have tried to insert into a table where not exists but again I get 4 rows inserted.
SELECT a.* from PAIRS a
inner join PAIRS b on a.no=b.no2 and a.no2=b.no;
I was thinking maybe selecting distinct number from column 1 and then check those in column 2 but I think that would yield the same four rows.
I may be over thinking this problem and maybe some here can look at this and see where the solution is hiding.
I am currently testing this on MySQL but it should run on SQLServer 2008. I have searched but all the questions didn't seem to match my data set issue.
Taking you at your word, meaning selecting all records where the value of no column does not appear anywhere in no2 column in the same table, try this:
SELECT A.PAIR_NO, A.NO, A.NO2
FROM PAIRS A
LEFT JOIN PAIRS B ON(A.NO = B.NO2)
WHERE B.PAIR_NO IS NULL -- assuming this column is not nullable
Another option is to use NOT EXISTS:
SELECT PAIR_NO, NO, NO2
FROM PAIRS A
WHERE NOT EXISTS(
SELECT 1
FROM PAIRS B
WHERE B.NO2 = A.NO
)
I personally prefer the LEFT JOIN option since it's shorter and more readable.
Both of these statement should work on both MySql and Sql Server.
Okay fellas I want to thank you all for helping, but I think I solved my issue. Took me a second but I believe this is what I am after (SQL Server 2008):
if OBJECT_ID('tempdb..#pairs') is not null drop table #pairs
if OBJECT_ID('tempdb..#pairs_final') is not null drop table #pairs_final
create table #pairs(pair_no int, a_no varchar(17),a_no2 varchar(17))
create table #pairs_final(pair_no int Identity(1,1), a_no varchar(17),a_no2 varchar(17))
insert into #PAIRS values(1,'1234ABCD','5678EFGH');
insert into #PAIRS values(1,'1234ABCD','XXXX9999');
insert into #PAIRS values(2,'0000AAAA','1111BBBB');
insert into #PAIRS values(3,'5678EFGH','1234ABCD');
insert into #PAIRS values(4,'1111BBBB','0000AAAA');
insert into #PAIRS values(1,'XXXX9999','1234ABCD');
insert into #pairs_final
select a.a_no,a.a_no2 from #pairs a
join (
select distinct a_no_p from(
select pair_no,a_no_p,
ROW_NUMBER() over (partition by pair_no order by a_no_p) as RN
from #pairs
unpivot(
a_no_p for clms in (a_no2,a_no)
) as umpvt
) as mypairs
where RN = 1
) as my_pairs on my_pairs.a_no_p=a.a_no
select * from #pairs_final
This will give me the following results:
pair_no a_no a_no2
1 1234ABCD 5678EFGH
2 1234ABCD XXXX9999
3 0000AAAA 1111BBBB
Hope this might help someone else.
Enjoy.
DECLARE #TBL AS TABLE
(
[NO] INT,
[CODE] VARCHAR(50),
[AREA] VARCHAR(50)
)
/* EXAMPLE 1 */
INSERT INTO #TBL([NO],[CODE],[AREA]) VALUES (1,'001','A00')
INSERT INTO #TBL([NO],[CODE],[AREA]) VALUES (2,'001','A00')
INSERT INTO #TBL([NO],[CODE],[AREA]) VALUES (3,'001','B00')
INSERT INTO #TBL([NO],[CODE],[AREA]) VALUES (4,'001','C00')
INSERT INTO #TBL([NO],[CODE],[AREA]) VALUES (5,'001','C00')
INSERT INTO #TBL([NO],[CODE],[AREA]) VALUES (6,'001','A00')
INSERT INTO #TBL([NO],[CODE],[AREA]) VALUES (7,'001','A00')
/* EXAMPLE 2 */
/* ***** USE THIS CODE TO ENTER DATA FROM DIRECT TABLE *****
SELECT
ROW_NUMBER() OVER(ORDER BY [FIELD_DATE]) AS [NO]
,[FIELD_CODE] AS [CODE]
,[FIELD_AREA] AS [AREA]
FROM TABLE_A
WHERE CAST([FIELD_DATE] AS DATE) >= CAST('20200307' AS DATE)
ORDER BY [FIELD_DATE],[FIELD_CODE]
*/
SELECT
A.NO AS ANO
,A.CODE AS ACODE
,A.AREA AS AAREA
,B.NO AS BNO
,B.CODE AS BCODE
,B.AREA AS BAREA
,CASE WHEN A.AREA=B.AREA THEN 'EQUAL' ELSE 'NOT EQUAL' END AS [COMPARE AREA]
FROM #TBL A
LEFT JOIN #TBL B
ON A.NO=B.NO+1

how to fetch data from more than one table? [duplicate]

This question already has an answer here:
how to fetch data from two tables in mysql?
(1 answer)
Closed 8 years ago.
I have to find out the output as name of students who have secured more than 70? My both tables are-
CREATE TABLE student(Fields_ID INT, Name VARCHAR(20));
INSERT INTO student(Fields_ID,Name) VALUES(30,'JYOTI');
INSERT INTO student(Fields_ID,Name) VALUES(31,'KIRTI');
INSERT INTO student(Fields_ID,Name) VALUES(32,'YOGITA');
INSERT INTO student(Fields_ID,Name) VALUES(33,'RASHMI');
INSERT INTO student(Fields_ID,Name) VALUES(34,'NUPUR');
SELECT * FROM student;
CREATE TABLE Marks(Fields_ID INT, Student_ID INT NOT NULL,marks INT NOT NULL);
INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (30,40,100);
INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (31,41,88);
INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (32,42,72);
INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (33,43,33);
INSERT INTO Marks(Fields_ID,Student_ID,Marks) VALUES (34,44,15);
SELECT * FROM Marks;
I was trying to return the required out from the following code but i was unable to form the logic. Any idea how to do it.I am a beginner in MySql so I am unable to find out the problem.
SELECT student.name,(select (marks>70) from marks)
From Student INNER JOIN marks
ON student.Fields_ID = marks.Fields_ID
GROUP BY student.name;
You can check conditions for groups with the having clause.. Use having to check if the sum of the marks reached your limit for every student.
SELECT student.name
From Student
INNER JOIN marks ON student.Fields_ID = marks.Fields_ID
GROUP BY student.name
HAVING sum(marks) > 70

how to copy one row data to another [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Update row with data from another row in the same table
I have created table as
create table myTable (id INT, myData varchar(20));
And I have values as
insert into myTable VALUES
(1, 'Value 1'),
(2, 'Value 2'),
(3, 'Value 3');
Now I insert row as
insert into myTable (id) values (4);
Now I want to insert data for id 4. Value for id 4 is same as id 3. SO I believe I need to use UPDATE statement.
I tried with below, however it won't work.
update myTable SET myData=(select myData FROM myTable WHERE id=3) WHERE id=4;
Please let me know what need to be done.
Demo at sqlfiddle
NOTE
Actually I have myData type as MEDIUMBLOB, however for demo purpose I used varchar.
In MySQL you can't update the same table your are selecting from. That leads to the error
You can't specify target table 'myTable' for update in FROM clause
But you can trick MySQL by creating a temp table
update myTable
SET myData=(select * from (select myData FROM myTable WHERE id=3) x)
WHERE id=4;
Can you not just use an inner join with aliased tables like this:
update myTable left_table
inner join myTable right_table ON right_table.id = 3
set left_table.myData = right_table.myData
where left_table.id = 4;
Updated fiddle

mysql -> insert into tbl (select from another table) and some default values [duplicate]

This question already has answers here:
How to do INSERT into a table records extracted from another table
(9 answers)
Closed 3 years ago.
As the title says, I am trying to insert into one table selecting values from another table and some default values.
INSERT INTO def (catid, title, page, publish)
(SELECT catid, title from abc),'page','yes')
INSERT INTO def (catid, title, page, publish)
VALUES
((SELECT catid, title from abc),'page','yes'))
The first query gives a mysql error and the second one gives column count does not match.
What do I need to do?
You simply have to do:
INSERT INTO def (catid, title, page, publish)
SELECT catid, title, 'page','yes' from `abc`
If you want to insert all the columns then
insert into def select * from abc;
here the number of columns in def should be equal to abc.
if you want to insert the subsets of columns then
insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc;
if you want to insert some hardcorded values then
insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc;
INSERT INTO def (field_1, field_2, field3)
VALUES
('$field_1', (SELECT id_user from user_table where name = 'jhon'), '$field3')
If you you want to copy a sub-set of the source table you can do:
INSERT INTO def (field_1, field_2, field3)
SELECT other_field_1, other_field_2, other_field_3 from `abc`
or to copy ALL fields from the source table to destination table you can do more simply:
INSERT INTO def
SELECT * from `abc`
With MySQL if you are inserting into a table that has a auto increment primary key and you want to use a built-in MySQL function such as NOW() then you can do something like this:
INSERT INTO course_payment
SELECT NULL, order_id, payment_gateway, total_amt, charge_amt, refund_amt, NOW()
FROM orders ORDER BY order_id DESC LIMIT 10;