6

Can I say that one of many ways to optimize mysql is to reduce the number of queries?

If that so, can I do this:

- Select "data" => $A from table X
- Update $A from table Y
- Delete $A from table X

in one query?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
webdev_007
  • 121
  • 3
  • 5
  • 9

3 Answers3

3

You can't reduce the number of queries - they all do different things - but you could reduce the number of round trips to the database and the number of parses by wrapping it all as a PLSQL function.

However you can't select the data after you've deleted it.....but consider:

CREATE PROCEDURE s_u_d(a)
BEGIN

UPDATE tab_x SET tab_x.avalue=1 WHERE tab_x.another=a;

DELETE FROM tab_y WHERE tab_y.avalue=a;

SELECT * 
FROM tab_x
WHERE tab_x.another=a;

END;

NB - you can also run multiple selects in the same procedure and handle multiple, different shaped result sets, e.g. see this page

symcbean
  • 47,736
  • 6
  • 59
  • 94
1

NO,
only can combine

  • DELETE and SELECT
  • UPDATE and SELECT

This is not a proper way for mysql optimization simply
because each query come with different query cost.

And in myisam, it involve table level locking for write

Example for UPDATE and SELECT

/* this will update TABLE_A if ID in TABLE_B exist in TABLE_A */
UPDATE TABLE_A, TABLE_B
  SET TABLE_A.SOME_COLUMN=TABLE_B.SOME_COLUMN
WHERE TABLE_A.ID=TABLE_B.ID

/* or */
UPDATE TABLE_A
  SET SOME_COLUMN = (SELECT SOME_COLUMN_B FROM TABLE_B WHERE ... LIMIT 1)

Example for DELETE and SELECT

DELETE FROM TABLE_A WHERE TABLE_A IN(SELECT ID FROM TABLE_B)
ajreal
  • 46,720
  • 11
  • 89
  • 119
0

Create a stored procedure:

DELIMITER // 

create procedure empproc(in name varchar(255),in fathername varchar(255),in password varchar(255))

begin

        Select * from xemp where uname = name and fname = fathername;

        insert into xemp values(name,fathername,password);

end //
delimiter ;

Java Code.....

import  java.sql.*;

public class StoredProcedure {

    public static void main(String a[])throws Exception {

        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/01jim2010","root","");
        CallableStatement calstat=conn.prepareCall("{call empproc(?,?,?)}");
        calstat.setString(1,"Jimit");
        calstat.setString(2,"Temp");
        calstat.setString(3,"Temp");

        ResultSet rs = calstat.executeQuery();
        conn.close();
        calstat.close();

        System.out.println("Your data has been inserted into table.");
      }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jimit Tank
  • 1,479
  • 5
  • 19
  • 25