how to write multiple select queries in single procedure? - mysql

I have to tables as:
table1:
UID | COLLEGE_NAME | COLLEGE_ADDRESS
------------------------------------
table2:
UID | COMPANY_NAME | COMPANY_ADDRESS
------------------------------------
i have 2 queries:
select * from table1 where uid='$uid';
select * from table2 where uid='$uid';
i want to write this two queries in one procedure.

structure for multiple select quires in single procedure:
CREATE PROCEDURE sample(l_uid INT) BEGIN
SELECT * FROM college_edu WHERE uid= l_uid;
SELECT * FROM work_experience WHERE uid= l_id;
END

Here's the statement to create STORED PROCEDURE.
DELIMITER $$
CREATE PROCEDURE procedureName(IN _uid VARCHAR(15))
BEGIN
SELECT UID, COLLEGE_NAME name, COLLEGE_ADDRESS address
FROM table1
WHERE uid = _uid
UNION ALL
SELECT UID, COMPANY_NAME name, COMPANY_ADDRESS address
FROM table2
WHERE uid = _uid
END $$
DELIMITER ;
notice that UNION has ALL keyword on it to add duplicate records on the result list. But if you prefer UNIQUE, remove the ALL keyword on the UNION.

below code may serve you purpose. Also the additional tbl column will let you know from which table your data is coming and it would help in further manipulation.
SELECT UID, COLLEGE_NAME name, COLLEGE_ADDRESS address , 1 as tbl
FROM table1
WHERE uid = _uid
UNION ALL
SELECT UID, COMPANY_NAME name, COMPANY_ADDRESS address , 2 as tbl
FROM table2
WHERE uid = _uid

Related

If exists is not printing pseudo values in SQL Server stored procedure

I am using a simple if exists statement in my stored procedure, but in output it is not printing the pseudo column values if the records does not exist.
SQL Server 2012
CREATE PROCEDURE test1
#Empid NVARCHAR(20)
AS
BEGIN
IF EXISTS (SELECT TOP 1 * FROM employees WHERE id = #Empid)
BEGIN
SELECT id, name, salary, 'Newemp' AS status, 1 AS Code
FROM employees
END
IF NOT EXISTS (SELECT TOP 1 * FROM employees WHERE id = #Empid)
BEGIN
SELECT id, name, salary, 'Oldemp' AS status1, 0 AS Code1
FROM employees
END
END
Result:
If record exists, this is returned as expected
ID Name Salary Status Code
-------------------------------
123 kkr 1000 Newemp 1
If the record doesn't exist - this is the problem:
Id Name Salary Status1 Code1
-----------------------------
Desired value:
ID Name Salary Status1 Code1
----------------------------
Oldemp 0
If the records doesn't exist, it is not printing the pseudo column values. I have changed the column names and executed to make sure that its taking the correct columns, and yes it is taking the correct ones, but failing to print the values.
Please help!
I did it myself, but Big thanks for your answers.
CREATE PROCEDURE test1
#Empid NVARCHAR(20)
AS
BEGIN
Create #temp
(Id Nvarchar(100),
Name Nvarchar(100),
Salary Nvarchar(100),
Status Nvarchar(100),
Code Nvarchar(100)
)
IF EXISTS (SELECT TOP 1 * FROM employees WHERE id = #Empid)
BEGIN
insert into #temp (id, name, salary)
values (SELECT id, name, salary
FROM employees WHERE id = #Empid)
Insert into # temp (Status , Code)
('Newemp', 1)
END
IF NOT EXISTS (SELECT TOP 1 * FROM employees WHERE id = #Empid)
BEGIN
insert into #temp (id, name, salary)
values (SELECT id, name, salary
FROM employees WHERE id = #Empid)
Insert into # temp (Status , Code)
('Oldemp', 0)
END
Select * from #temp
END
These queries are based on the number of records in employees - it could be one, it could be none, and it could be many. If you always want to get a single row, you can omit the from clause and just select literals:
SELECT NULL AS id, NULL AS name, NULL AS salary, 'Oldemp' ASs status1, 0 AS Code1

How to merge multiple select statement result into single select statement?

I have write stored procedure given below.
ALTER PROCEDURE StudentDemo #RollNo INT
/*
StudentDemo 504
*/
AS
BEGIN
DECLARE #CurrentID INT
--Get the Current RollNo's ID
SELECT #CurrentID = ID FROM StudentData WHERE RollNo = #RollNo
SELECT #CurrentID AS 'CurrentID'
--Previous ID
SELECT RollNO AS 'PreviousID' FROM StuDentData WHERE ID = #CurrentID - 1
--Next ID
SELECT RollNO AS 'NextID' FROM StuDentData WHERE ID = #CurrentID + 1
END
I want all the result of select statement in single one and put result in temporary table

select statement stored procedure in mysql

I have three tables in database:
user_tbl: userID | name | email | password
task_tbl: taskID | description | Date
usertask_tbl: userID | taskID
Now i want to display all the tasks related to one user, it should go and get check the taskid of that user and show all the description and date for that user. But instead its showing one description and date.
Here is my stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `alltask`(IN `useremail` INT(11))
BEGIN
SELECT #userID := userID FROM user_tbl WHERE email=useremail;
SELECT #TaskID :=taskID from usertask_tbl WHERE userID = #userID;
SELECT description, Date from task_tbl WHERE taskID = #TaskID;
END
I'm new to this. If this is not the right way to do it please help me.
You are only selecting one task when you do:
SELECT #TaskID :=taskID from usertask_tbl WHERE userID = #userID;
Therefore, instead of:
SELECT #TaskID :=taskID from usertask_tbl WHERE userID = #userID;
SELECT description, Date from task_tbl WHERE taskID = #TaskID;
Try:
SELECT description, Date from task_tbl AS t1
INNER JOIN usertask_tbl AS t2 ON t1.taskID = t2.taskID
WHERE userID = #userID;

How to fetch rows in column manner in sql?

I have a record in my table like
memberId PersonId Year
4057 1787 2
4502 1787 3
I want a result from a query like this
memberId1 MemberId2 PersonId
4057 4502 1787
How to write a query ??
Don't do this in a query, do it in the application layer.
Don't do this in SQL. At best you can try:
SELECT table1.memberId memberId1, table2.memberId MemberId2, PersonId
FROM table table1 JOIN table table2 USING (PersonId)
But it won't do what you expect if you have more than 2 Members for a person. (It will return every possible combination.)
Below an example on how to do it directly in SQL. Mind that there is plenty of room for optimisation but this version should be rather fast, esp if you have an index on PersonID and year.
SELECT DISTINCT PersonID,
memberId1 = Convert(int, NULL),
memberId2 = Convert(int, NULL)
INTO #result
FROM myTable
WHERE Year IN (2 , 3)
CREATE UNIQUE CLUSTERED INDEX uq0_result ON #result (PersonID)
UPDATE #result
SET memberId1 = t.memberId
FROM #result upd
JOIN myTable t
ON t.PersionId = upd.PersonID
AND t.Year = 2
UPDATE #result
SET memberId2 = t.memberId
FROM #result upd
JOIN myTable t
ON t.PersionId = upd.PersonID
AND t.Year = 3
SELECT * FROM #result
if you want all member ids for each person_id, you could use [for xml path] statement (great functionality)
to concat all memberId s in a string
select distinct PersonId
, (select ' '+cast(t0.MemberId as varchar)
from table t0
where t0.PersonId=t1.PersonId
for xml path('')
) [Member Ids]
from table t1
resulting in:
PersonId Members Ids
1787 ' 4057 4502'
if you really need seperate columns, with unlimited number of memberIds, consider using
a PIVOT table, but far more complex to use

MySQL delete duplicate records but keep latest

I have unique id and email fields. Emails get duplicated. I only want to keep one Email address of all the duplicates but with the latest id (the last inserted record).
How can I achieve this?
Imagine your table test contains the following data:
select id, email
from test;
ID EMAIL
---------------------- --------------------
1 aaa
2 bbb
3 ccc
4 bbb
5 ddd
6 eee
7 aaa
8 aaa
9 eee
So, we need to find all repeated emails and delete all of them, but the latest id.
In this case, aaa, bbb and eee are repeated, so we want to delete IDs 1, 7, 2 and 6.
To accomplish this, first we need to find all the repeated emails:
select email
from test
group by email
having count(*) > 1;
EMAIL
--------------------
aaa
bbb
eee
Then, from this dataset, we need to find the latest id for each one of these repeated emails:
select max(id) as lastId, email
from test
where email in (
select email
from test
group by email
having count(*) > 1
)
group by email;
LASTID EMAIL
---------------------- --------------------
8 aaa
4 bbb
9 eee
Finally we can now delete all of these emails with an Id smaller than LASTID. So the solution is:
delete test
from test
inner join (
select max(id) as lastId, email
from test
where email in (
select email
from test
group by email
having count(*) > 1
)
group by email
) duplic on duplic.email = test.email
where test.id < duplic.lastId;
I don't have mySql installed on this machine right now, but should work
Update
The above delete works, but I found a more optimized version:
delete test
from test
inner join (
select max(id) as lastId, email
from test
group by email
having count(*) > 1) duplic on duplic.email = test.email
where test.id < duplic.lastId;
You can see that it deletes the oldest duplicates, i.e. 1, 7, 2, 6:
select * from test;
+----+-------+
| id | email |
+----+-------+
| 3 | ccc |
| 4 | bbb |
| 5 | ddd |
| 8 | aaa |
| 9 | eee |
+----+-------+
Another version, is the delete provived by Rene Limon
delete from test
where id not in (
select max(id)
from test
group by email)
Try this method
DELETE t1 FROM test t1, test t2
WHERE t1.id > t2.id AND t1.email = t2.email
Correct way is
DELETE FROM `tablename`
WHERE `id` NOT IN (
SELECT * FROM (
SELECT MAX(`id`) FROM `tablename`
GROUP BY `name`
)
)
DELETE
FROM
`tbl_job_title`
WHERE id NOT IN
(SELECT
*
FROM
(SELECT
MAX(id)
FROM
`tbl_job_title`
GROUP BY NAME) tbl)
revised and working version!!! thank you #Gaurav
If you want to keep the row with the lowest id value:
DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE n1.id > n2.id AND n1.email = n2.email
If you want to keep the row with the highest id value:
DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE n1.id < n2.id AND n1.email = n2.email
or this query might also help
DELETE FROM `yourTableName`
WHERE id NOT IN (
SELECT * FROM (
SELECT MAX(id) FROM yourTableName
GROUP BY name
)
)
I must say that the optimized version is one sweet, elegant piece of code, and it works like a charm even when the comparison is performed on a DATETIME column. This is what I used in my script, where I was searching for the latest contract end date for each EmployeeID:
DELETE CurrentContractData
FROM CurrentContractData
INNER JOIN (
SELECT
EmployeeID,
PeriodofPerformanceStartDate,
max(PeriodofPerformanceEndDate) as lastDate,
ContractID
FROM CurrentContractData
GROUP BY EmployeeID
HAVING COUNT(*) > 1) Duplicate on Duplicate.EmployeeID = CurrentContractData.EmployeeID
WHERE CurrentContractData.PeriodofPerformanceEndDate < Duplicate.lastDate;
Many thanks!
I personally had trouble with the top two voted answers. It's not the cleanest solution but you can utilize temporary tables to avoid all the issues MySQL has with deleting via joining on the same table.
CREATE TEMPORARY TABLE deleteRows;
SELECT MIN(id) as id FROM myTable GROUP BY myTable.email;
DELETE FROM myTable
WHERE id NOT IN (SELECT id FROM deleteRows);
DELIMITER //
CREATE FUNCTION findColumnNames(tableName VARCHAR(255))
RETURNS TEXT
BEGIN
SET #colNames = "";
SELECT GROUP_CONCAT(COLUMN_NAME) FROM INFORMATION_SCHEMA.columns
WHERE TABLE_NAME = tableName
GROUP BY TABLE_NAME INTO #colNames;
RETURN #colNames;
END //
DELIMITER ;
DELIMITER //
CREATE PROCEDURE deleteDuplicateRecords (IN tableName VARCHAR(255))
BEGIN
SET #colNames = findColumnNames(tableName);
SET #addIDStmt = CONCAT("ALTER TABLE ",tableName," ADD COLUMN id INT AUTO_INCREMENT KEY;");
SET #deleteDupsStmt = CONCAT("DELETE FROM ",tableName," WHERE id NOT IN
( SELECT * FROM ",
" (SELECT min(id) FROM ",tableName," group by ",findColumnNames(tableName),") AS tmpTable);");
set #dropIDStmt = CONCAT("ALTER TABLE ",tableName," DROP COLUMN id");
PREPARE addIDStmt FROM #addIDStmt;
EXECUTE addIDStmt;
PREPARE deleteDupsStmt FROM #deleteDupsStmt;
EXECUTE deleteDupsStmt;
PREPARE dropIDStmt FROM #dropIDStmt;
EXECUTE dropIDstmt;
END //
DELIMITER ;
Nice stored procedure I created for deleting all duplicate records of a table without needing an existing unique id on that table.
CALL deleteDuplicateRecords("yourTableName");
I want to remove duplicate records based on multiple columns in table, so this approach worked for me,
Step 1 - Get max id or unique id from duplocate records
select * FROM ( SELECT MAX(id) FROM table_name
group by travel_intimation_id,approved_by,approval_type,approval_status having
count(*) > 1
Step 2 - Get ids of single records from table
select * FROM ( SELECT id FROM table_name
group by travel_intimation_id,approved_by,approval_type,approval_status having
count(*) = 1
Step 3 - Exclude above 2 queries from delete to
DELETE FROM `table_name`
WHERE
id NOT IN (paste step 1 query) a //to exclude duplicate records
and
id NOT IN (paste step 2 query) b // to exclude single records
Final Query :-
DELETE FROM `table_name`
WHERE id NOT IN (
select * FROM ( SELECT MAX(id) FROM table_name
group by travel_intimation_id,approved_by,approval_type,approval_status having
count(*) > 1) a
)
and id not in (
select * FROM ( SELECT id FROM table_name
group by travel_intimation_id,approved_by,approval_type,approval_status having
count(*) = 1) b
);
By this query only duplocate records will delete.
Please try the following solution (based on the comments of the '#Jose Rui Santos' answer):
-- Set safe mode to false since;
-- You are using safe update mode and tried to update a table without a WHERE that uses a KEY column
SET SQL_SAFE_UPDATES = 0;
-- Delete the duplicate rows based on the field_with_duplicate_values
-- Keep the unique rows with the highest id
DELETE FROM table_to_deduplicate
WHERE id NOT IN (
SELECT * FROM (
-- Select the highest id grouped by the field_with_duplicate_values
SELECT MAX(id)
FROM table_to_deduplicate
GROUP BY field_with_duplicate_values
)
-- Subquery and alias needed since;
-- You can't specify target table 'table_to_deduplicate' for update in FROM clause
AS table_sub
);
-- Set safe mode to true
SET SQL_SAFE_UPDATES = 1;