I have a few tables with exact same schema, the only reason its separate is because they are huge.
So if i do a
select * from
(select * from ptable p1
union select * from ptable2 p2
.. and so on) pp
where pid=1234
, it will take really long time.
I like to write a one where i check ptable(s) for pid value of 1234, if it exist, then select the row from the right table.
How do i do that? pid is unique and will only exist in one table, it is also not in any sorted order.
I manage to solve my problem after some experiment, not sure if its the best way being an amateur but it works.
CREATE PROCEDURE 'sproc'(IN pQryID INT)
BEGIN
select count(*) as count into #rowCountp1 from p1 where pid=pQryID;
select count(*) as count into #rowCountp2 from p2 where pid=pQryID;
.. and so on for other similar tables ..
if #rowCountp1>0 THEN
(SELECT * from p1 where pid=pQryID);
elseif #rowCountp2>0 THEN
(SELECT ( from p2 where pid=pQryID);
end if;
END
Related
In mySQL stored procedure how can I assign a Query String to a variable, so I can reuse it? In my example I will be using SELECT id FROM audit many times.
CREATE PROCEDURE my_proc()
BEGIN
UPDATE person SET status='Active' WHERE id = (SELECT id FROM audit);
SELECT COUNT(*) FROM (SELECT id FROM audit);
//Multile scenarios the `SELECT id FROM audit` will be used.
END
Something like:
CREATE PROCEDURE my_proc()
BEGIN
myVariable = SELECT id FROM audit;
UPDATE person SET status='Active' WHERE id = (myVariable;
SELECT COUNT(*) FROM (myVariable);
//Multile scenarios the `SELECT id FROM audit` will be used.
END
Is this what you are looking for? Sorry I am not sure what you need.
SELECT #myCount:= count(id) FROM audit;
select #myCount;
Based on your reply, do you need a temporary table to store the ids from the audit and re-use those on the queries?
create temporary table tbl_tmp_audit;
select id from audit;
I am assuming you need this so that you won't join the whole audit columns every time on your succeeding queries.
--first query
UPDATE person AS p
INNER JOIN tbl_tmp_audit t ON p.id = t.id
SET status = 'Active';
--second query
SELECT COUNT(*) FROM tbl_tmp_audit;
Drop temporary table tbl_temp_bookings;
Is it possible to create a trigger that conditionally updates a column with a random value from another tables column.
Previously I received help to create a trigger that updates a column with a random value from another tables column: MySQL: Trigger Update with random value from another tables column. I’m trying now to make it conditionally based on another columns value.
If the users.selection column = ‘fruits’ then random select from fruits.
If the users.selection column = ‘animals’ then random from animals.
If neither ‘fruits’ nor ‘animals’ don’t update.
Here is a db-fiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=6bc76ed2c104dad0e27dd35b1da112a7
Major thanks to #Akina for getting me this far! Lots to learn.
Update (May 29th):
I still can’t figure it out. I thought maybe I would need a SELECT with IF statement first to return the selection column value but that didn’t seem to work. Basically I have tried a lot of different combinations using these examples below as templates. None of them seem to bring my closer.
Anyone have any ideas?
Examples:
SELECT T1.ID, IFNULL(T1.name, T2.name) AS name
FROM firsttable T1
LEFT JOIN secondtable T2
ON T1.T2_id = T2.id
SET final_price= CASE
WHEN currency=1 THEN 0.81*final_price
ELSE final_price
END
SET col = (
SELECT other_col
FROM other_table
WHERE other_table.table_id = table.id
);
SELECT book_name,isbn_no,
IF((SELECT COUNT(*) FROM book_mast WHERE pub_lang='English')>
(SELECT COUNT(*) FROM book_mast WHERE pub_lang<>'English'),
(CONCAT("Pages: ",no_page)),(CONCAT("Price: ",book_price)))
AS "Page / Price"
FROM book_mast;
I think you need to conditionally define what does what, if selection is fruit, then do something. else if selection is animals, then do another thing.
e.g:
CREATE TRIGGER trigger_test
BEFORE UPDATE
ON users
FOR EACH ROW
BEGIN
IF (NEW.selection = 'fruits') THEN
SET NEW.random = ( SELECT fruits
FROM list
ORDER BY RAND() LIMIT 1 );
ELSEIF (NEW.selection = 'animals') THEN
SET NEW.random = ( SELECT animals
FROM list
ORDER BY RAND() LIMIT 1 );
END IF;
END;
I have two tables. The left side table is Bin and the Right side table is Bout. In_id means an order in which they are batting, Out_id means an order in which they are out from the game. Report1 below shows the answer I want, i.e. those who made a partnership. I am not getting any idea on how to write a query to retrieve the data which is in report 1. That is the answer I actually want. How to write a query for that? Your help would be appreciated!
This is multi step approach. table 1 refers to left side table i.e. batting id table and table 2 refers to right side table i.e out id table in your data.
new.table1, new.table2, new.table3, new.table4 are temporary table. Correct column name as per your data. Hope you will get your result. Comment if find any issue.
Create temporary table new.table1
select OUT.ID, IN.ID, Name, (IN.ID - OUT.ID) AS DIFF from table2;
Create temporary table new.table2
select OUT.ID, IN.ID, Name, (OUT.ID + 1) AS NEW.ID from new.table1 where DIFF <= 0;
Create temporary table new.table3
select OUT.ID, IN.ID, Name, DIFF AS NEW.ID from new.table1 where DIFF > 0;
Create temporary table new.table4
select OUT.ID, IN.ID, Name, NEW.ID from new.table2
UNION ALL
select OUT.ID, IN.ID, Name, NEW.ID from new.table3;
---Final Output
select A.Name, B.Name AS Name2 from new.table4 A, table1 B where A.NEW.ID = B.IN.ID;
select
s1.names,
s2.names
from
IN_TABLE,
OUT_TABLE s1,s2
where
s1.IN_ID = s2.IN_ID;
(where s1 and s2 are alias)
or
select
left_table.name,
right_table.name as Report1
from
left_table,
right_table
where
left_table.IN_ID = right_table.IN_ID
please try and let us know if this solves your problem.
Also, see https://www.youtube.com/watch?v=KTvYHEntvn8 for more knowledge.
You need a join or a subquery.
Lets take a look of a join
Select
leftTable.Name,
rightTable.Name
from
leftTable
join rightTable
on leftTable.IN_ID = rightTable.In_ID
Edited: left to leftTable and right to rightTable
I need to update a table, but to get the new value it seems that I need to create a temporary table. The reason is that I need to calculate sum of the max. Can I do it?
The pseudocode looks like this:
UPDATE users u SET usersContribution = [CREATE TEMPORARY TABLE IF NOT EXISTS tmpTbl3 AS
(SELECT ROUND(max(zz.zachetTimestamp - d.answerDate)) as answerDateDiff
FROM zachet zz
JOIN discussionansw d ON d.zachetid=zz.zachetId and d.usersid=zz.usersId and
zz.zachetTimestamp > d.answerDate
WHERE zz.whoTalk=u.userid and
NOT EXISTS (SELECT * FROM discussionansw
WHERE zachetid=zz.zachetId and usersid=u.userid')
GROUP BY zz.zachetId)]
SELECT SUM(answerDateDiff) FROM tmpTbl3;"
I used a brackets to show the part, which have to be done, but ignored by UPDATE query...
I have both max and sum and I do not see a way to avoid tmp table. But if you can I we'll be glad to have such a solution.
I put here THE ANSWER, which I get with help of #flaschenpost and this post: SQL Update to the SUM of its joined values
CREATE TEMPORARY TABLE IF NOT EXISTS t0tmpTbl3 AS
(SELECT zz.whoTalk, ROUND(max(zz.zachetTimestamp - d.answerDate)) as answerDateDiff
FROM zachet zz
JOIN discussionansw d ON d.zachetid=zz.zachetId and d.usersid=zz.usersId and
zz.zachetTimestamp > d.answerDate
WHERE
NOT EXISTS (SELECT * FROM discussionansw WHERE zachetid=zz.zachetId and usersid=zz.whoTalk)
GROUP BY zz.zachetId);
UPDATE users u
JOIN (SELECT whoTalk, SUM(answerDateDiff) sumAnswerDateDiff
FROM t0tmpTbl3 GROUP BY whoTalk) t
ON u.usersId=t.whoTalk
SET u.usersContribution=sumAnswerDateDiff;
Could you just break it into two Queries?
drop temporary table if exists tmp_maxsumofsomething;
create temporary table tmp_maxsumofsomething
select max(), sum(), ...
from zachet z inner join discussionansw a on ...
group by...
;
update u inner join tmp_maxsumofsomething t on ... set u.... = t...
Temporary Tables are just visible in the connection where they have been created, so Thread Safety is given.
EDIT: As long as your Queries make any sense, you could try:
DROP TEMPORARY TABLE IF EXISTS tmpTbl3;
CREATE TEMPORARY TABLE tmpTbl3
SELECT zz.whoTalk as userId, ROUND(max(zz.zachetTimestamp - d.answerDate)) as answerDateDiff
FROM zachet zz, discussionansw d
WHERE d.zachetid=zz.zachetId
and d.usersid=zz.usersId and zz.zachetTimestamp > d.answerDate
# What do you mean ? by:
# and (SELECT count(*) FROM discussionansw
# WHERE zachetid=zz.zachetId and usersid=u.userid) = 0
# Think about a reasonable WHERE NOT EXISTS clause!
GROUP BY zz.whoTalk
Then you have your Temp-Table to join to:
update users u
inner join tmpTbl3 tm on u.userId = tm.userId
set u.usersContribution = tm.answerDateDiff
If you are brave enough to write an application needing those queries, you should not be scared to learn a bit more of some concepts of SQL and MySQL. You are here for the exploration of concepts, not to hire Programmers for free.
I have a table A with one column named a, and a file "test.txt" contains:
111111AAAA
222222BBBB
3333DDDDDD
.....
The records in test.txt have the same type with "a" column.
How to select all from A except the records in "test.txt"?
Update:
I tried 3 ways and the results not equal. What a strange!
// 7073 records -- Using NOT IN
SELECT * from mt_users WHERE TERMINAL_NUMBER_1 NOT IN (SELECT TERMINAL_NUMBER FROM A);
// 7075 records -- Using NOT EXISTS
SELECT * from mt_users WHERE NOT EXISTS (SELECT 1 FROM A WHERE A.TERMINAL_NUMBER = mt_users.TERMINAL_NUMBER_1);
// 7075 records -- Using LEFT JOIN
SELECT * FROM mt_users m LEFT JOIN A a ON m.TERMINAL_NUMBER_1 = a.TERMINAL_NUMBER WHERE a.TERMINAL_NUMBER IS NULL;
Firstly put all records from file into the newTable and make sure that there are no additional spaces at the beginning or the end in each field.
select a from tableA t where not exists(select 1 from newTable n where n.a = t.a)
Step 1. Put the records from test.txt into a different table.
Step 2.
SELECT a from tableA WHERE a NOT EXISTS (SELECT a FROM newTable)
doing what aF wrote would be my first answer too. if you cant/do not want to do that try "NOT IN" like:
SELECT a FROM A WHERE a NOT IN(...)
You have to generate the content of the () in the code where you create your query