Does Anyone Know SQL

incman

New Member
Messages
2
Reaction score
0
Points
0
Hi

Does anyone know sql enough to lend me a hand.

I just want to know how I can simply locate the last record in a table and the move that record into a new table.

I've been trying for a couple of weeks now and no success.

Thanks in advance.
 

MaXiMiUS

New Member
Messages
9
Reaction score
0
Points
0
Here's some PHP that may help:
Code:
<?php
$link = mysql_connect("host","user","pass");
mysql_select_db("db_name",$link);
$selectSQL = "SELECT * FROM `sometable` ORDER BY `order_column` DESC LIMIT 1;"; // Remove or change the LIMIT 1 depending on how many rows you would like to move to the other table
$query = mysql_query($selectSQL,$link);
while($row = mysql_fetch_object($query)){
    $deleteSQL = "DELETE FROM `sometable` WHERE `identifying_column` = '".($row->identifying_column)."';";
    $updateSQL = "INSERT INTO `othertable`(`identifying_column`,`order_column`,`column3`,`column4`) VALUES('".($row->identifying_column)."','".($row->order_column)."','".($row->column3)."','".($row->column4)."');";
    mysql_query($deleteSQL,$link);
    mysql_query($updateSQL,$link);
}
?>

Edit: What you're asking to do -could- be done with only SQL, but I don't think it could be done in a single query. You'd basically have to do the same thing the PHP code is doing here.
 
Last edited:

zen-r

Active Member
Messages
1,937
Reaction score
3
Points
38
This thread shouldn't be in the Off-Topic category.
 

Kayos

Community Advocate
Community Support
Messages
987
Reaction score
4
Points
0
This thread shouldn't be in the Off-Topic category.

Reporting the post helps us moderators put threads in the correct place.

-Moved to Programming Help-
 

zen-r

Active Member
Messages
1,937
Reaction score
3
Points
38
Reporting the post helps us moderators put threads in the correct place.

-Moved to Programming Help-

I've always wondered about that.

So it's OK to use the "Report Post" icon for that then?

It says "Note: This is ONLY to be used to report spam, advertising messages, and problematic (harassment, fighting, or rude) posts." & since this doesn't come under any of those categories, I didn't want to use the Report Post icon if I wasn't supposed to.

What about threads that we think should be closed (not because they're spam or abusive, but for other reasons -eg(1) the poster is starting duplicate threads of the same question/ topic, or eg(2) because an original offer has closed but noobs keeps thinking the offer is still running & keep adding new posts to the end of a thread)? Should the icon be used then also? Or should we just wait for a Mod to find those threads themselves?
 
Last edited:

Kayos

Community Advocate
Community Support
Messages
987
Reaction score
4
Points
0
I've always wondered about that.

So it's OK to use the "Report Post" icon for that then?

It says "Note: This is ONLY to be used to report spam, advertising messages, and problematic (harassment, fighting, or rude) posts." & since this doesn't come under any of those categories, I didn't want to use the Report Post icon if I wasn't supposed to.

What about threads that we think should be closed (not because they're spam or abusive, but for other reasons -eg(1) the poster is starting duplicate threads of the same question/ topic, or eg(2) because an original offer has closed but noobs keeps thinking the offer is still running & keep adding new posts to the end of a thread)? Should the icon be used then also? Or should we just wait for a Mod to find those threads themselves?

It's fine to report a message saying that a thread is in the wrong place, especially if you see a thread in the same place for days on end. I try to move everything eventually but I can't be here all day long. :(


And with reporting closing threads:

1. Duplicate threads can be considered spam so yes you can report them.

2. Those type of threads are solely at the discretion of the moderators.

If you would like to discuss this more please PM me. :)
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Edit: What you're asking to do -could- be done with only SQL, but I don't think it could be done in a single query. You'd basically have to do the same thing the PHP code is doing here.
It can be done in two by using INSERT ... SELECT followed by DELETE, but (as you surmise) not one.

This looks like it needs transactions to prevent duplicates in the tables if the DELETE fails to execute.

Code:
START TRANSACTION;
INSERT INTO [I]target[/I] SELECT * FROM [I]source[/I] ORDER BY [I]col[/I] DESC LIMIT 1;
DELETE FROM [I]source[/I] ORDER BY [I]col[/I] DESC LIMIT 1;
COMMIT;

As long as there's an index on col, the two ORDER BY clauses won't drag down performance.
 
Last edited:

Twinkie

Banned
Messages
1,389
Reaction score
12
Points
0
It can be done in two by using INSERT ... SELECT followed by DELETE, but (as you surmise) not one.

This looks like it needs transactions to prevent duplicates in the tables.

Code:
START TRANSACTION;
INSERT INTO [I]target[/I] SELECT * FROM [I]source[/I] ORDER BY [I]col[/I] DESC LIMIT 1;
DELETE FROM [I]source[/I] ORDER BY [I]col[/I] DESC LIMIT 1;
COMMIT;
As long as there's an index on col, the two ORDER BY clauses won't drag down performance.
It is good practice misson to separate subqueries with (), but I think a SELECT INTO statement would be better suited to this.
Code:
SELECT *
INTO new_table_name
FROM old_tablename
WHERE [I]condition[/I]
LIMIT 1;

DELETE
FROM [I]source[/I]
WHERE [I]condition[/I]
LIMIT 1;
This would probably be faster because it eliminates the need for a separate query.

About the transactions I am not sure. I thought that it required logic in PHP in order for you to decide whether to issue a ROLLBACK command when you start a transaction? Or maybe the BEGIN - ROLLBACK - COMMIT syntax is specific to MySQL.

Make sure you have the appropraite table type (InnoDB) for transactions which must be specified in the table's creation. The default MyISAM will not work with transactions.
Code:
TABLE (
....
) type=innodb;
 
Last edited:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
It is good practice misson to separate subqueries with (),
The SELECT in INSERT ... SELECT isn't exactly a subquery, so I didn't bother.

but I think a SELECT INTO statement would be better suited to this.
MySQL doesn't support SELECT ... INTO.

This would probably be faster because it eliminates the need for a separate query.
Both SELECT ... INTO and INSERT ... SELECT require a search and an insert, and will thus perform similarly.

About the transactions I am not sure. I thought that it required logic in PHP in order for you to decide whether to issue a ROLLBACK command when you start a transaction? Or maybe the BEGIN - ROLLBACK - COMMIT syntax is specific to MySQL.[/CODE]
A ROLLBACK is only sent to discard the changes introduced by a transaction; it shouldn't be needed here. Since the OP never mentioned anything other than SQL, I didn't bother with any other language.


@OP: another reason transactions are necessary here is that when you use a single query to copy a row from one table to another, you don't get a unique field that you can use in a DELETE query. Instead, you have to use the same selection clause in both statements. Another query could execute between the INSERT and DELETE, changing the row matched by the selection clause and thus causing the wrong row to get deleted.
 

Twinkie

Banned
Messages
1,389
Reaction score
12
Points
0
:bash: w3schools.com

It doesn't always make the lines clear between MySQL and SQL.

BTW: SQL is a standard and MySQL is a language, so when you ask for SQL help in Google, your results will work only half the time.

I still don't understand why to use a transaction if it cannot rollback. Does it do this automatically from within the query?
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
:bash: w3schools.com

It doesn't always make the lines clear between MySQL and SQL.
Or even SQL standards and extensions. The INTO clause isn't even standard. To be fair, SQL support in DBMSs is worse than browser support for web standards; it's tricky to the point of being pointless to cover all the whys and wherefores.

I still don't understand why to use a transaction if it cannot rollback. Does it do this automatically from within the query?
You can rollback the transaction, it's just that that isn't why I suggested it. The transaction is to make the queries atomic. You could also lock the tables explicitly, but a transaction should perform better because MySQL can delay locking until it has all the statements in the transaction.

One potential difference between SELECT ... INTO TABLE and INSERT ... SELECT (for DBMSs that support both) is that one, both or neither might use temporary tables.
 

incman

New Member
Messages
2
Reaction score
0
Points
0
Many thanks for all your suggestions.

I have decided to use a function because I some other calculations I need to process once I have managed to transfer the data over.

function addMem($username, $email){
$q = "INSERT INTO".TBL_MEMBERS. "VALUES (‘‘, $username, $email)
SELECT username, email
FROM" .TBL_USERS. "ORDER BY timestamp DESC LIMIT 1";
return mysql_query($q,$this->connection);

As far as I can see this should work. But it doesn't.

Any more suggestions?

Thanks
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
When posting code, use the
Code:
, [html] or [php] tags as appropriate.

If you're generating an SQL query that isn't working, check the generated statement. If you don't have a PHP debugger (e.g. [URL="http://phpandtips.wordpress.com/2009/02/15/eclipse-pdtxdebug/"]Eclipse+PDT+XDebug[/URL]), add some scaffolding to the script to print the statement . You'll see something like:
[quote]INSERT INTOmembersVALUES (‘‘, bob, [email]bob@example.net[/email]) 
                SELECT username, email 
                FROMusersORDER BY timestamp DESC LIMIT 1[/quote]
As you see, this has numerous problems. There's no space around the table names. You've mixed the [FONT="Courier New"]INSERT ... VALUES[/FONT] and [FONT="Courier New"]INSERT ... SELECT[/FONT] statements. You've left out the column names. Each of those makes the statement syntactically invalid. If you had included column names, either the [FONT="Courier New"]VALUES[/FONT] clause would have one too many column values or the SELECT clause would have one too few. In the [FONT="Courier New"]VALUES[/FONT] clause, you've left two of the column values unquoted, which is a logic error (it can potentially cause runtime errors). The first column uses the wrong quotes. 

Study the syntax of [URL="http://dev.mysql.com/doc/refman/5.1/en/insert.html"][FONT="Courier New"]INSERT[/FONT][/URL] more closely.
 
Top