I am attempting to return the value of the row for this statement:
INSERT INTO SystemName (SystemName)
SELECT * FROM (SELECT v_SystemName) AS tmp
WHERE NOT EXISTS (
SELECT * FROM SystemName WHERE SystemName = v_SystemName
) LIMIT 1;
SET id = LAST_INSERT_ID();
If it actually does the insert I need it to return that row ID, otherwise it needs to return the new row ID. I tried to use LAST_INSERT_ID() but that didn't return what I needed because if it didn't do the insert it would give the wrong result. Does anyone have an idea that could make this work?
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
Assuming your procedure only expects back the row ID and no further processing will be done you can try: SELECT LAST_INSERT_ID();
So, what I ended up doing was this, and I know it isn't the best solution because it isn't a transaction and could cause some issues but this is the only way I could get it to work.
INSERT INTO SystemName (SystemName)
SELECT * FROM (SELECT v_SystemName) AS tmp
WHERE NOT EXISTS (
SELECT * FROM SystemName WHERE SystemName = v_SystemName
) LIMIT 1;
SELECT id FROM SystemName WHERE SystemName = v_SystemName;
This way I don't need any out variables or anything, it just returns my id.
Related
I want to select a bunch of rows from a mysql database and update the viewed attribute of those once selected (this is a kind of 'I have read these' flag).
Initially I did something like this:
update (
select a, b, c
from mytable
where viewed = '0'
)
set viewed = '1';
This selects the rows nicely and updates their viewed attribute as required. But it does not return the selected rows from the subquery.
Is there a clause I can add, or perhaps I need to store the subquery, etc...? I did consider a transaction but I ended up with the same problem. I have not tried a stored procedure...
Please can someone advise / point me in the right direction on how to do what I do above but in addition return the selected tables from the subquery?
Thanks in advance.
Update:
As pointed out by #Barmar, #a_horse_with_no_name, #fancyPants and #George Garchagudashvil...
In MySQL you have to use two statements to select and update, and not a nested statement as in my initial post, if you want to return the selected rows.
e.g.
begin;
select a, b, c
from mytable
where viewed = '0';
update mytable
set viewed = '1'
where viewed = '0';
commit;
thanks guys.
I would create a simple function:
DELIMITER $$
DROP FUNCTION IF EXISTS `mydb`.`updateMytable`$$
CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
FUNCTION `mydb`.`updateMytable`() RETURNS TEXT
BEGIN
SET #updated := '';
UPDATE mytable
SET viewed = 1
WHERE viewed = 0
AND (
SELECT #updated := CONCAT_WS(',', #updated, id)
) != ''
;
RETURN TRIM(LEADING ',' FROM #updated);
END$$
DELIMITER ;
which updates tables and returns concatenated ids.
From php you call this:
SELECT mydb.updateMytable()
and you get ids in a stirng: 1,2,7,54,132 etc...
Update:
my function is returning string containing comma separated ids:
'1,5,7,52,...' these ids are only which would have been updated during the function call,
better php-mysql example would be (you may and would use PDO):
$query = "SELECT mydb.updateMytable()";
$res = mysql_query($query);
$arr = mysql_fetch_array($res);
$ids = explode(',', $arr[0]);
// now you can do whatever you want to do with ids
foreach ($ids as $id)
{
echo "Hoorah: updated $id\n";
}
also remember to change mydb and mytable according to your database names
Final
because you need more complex functionality, simply run two query:
First run:
SELECT a, b, c
FROM mytable
WHERE viewed = 0
Next run:
UPDATE mytable
SET viewed = 1
WHERE viewed = 0
I have a MYSQL table and two of the fields are called Rate_per_unit and Cost. First I want the field Rate_per_unit to populate itself from another table called SHD_TEACHER then I want the field COST to populate itself also from RATE in SHD_TEACHER and multiplies by UNITS.
I have the following code which is giving me an error:
CREATE TRIGGER RATE_PER_UNIT_1
BEFORE INSERT ON SHD_SCHEDULE
FOR EACH ROW
SET NEW.RATE_PER_UNIT =
(
SELECT RATE
FROM SHD_TEACHER
WHERE TEACHERID = NEW.TEACHER_ID
LIMIT 1
)
SET NEW.COST = (
SELECT RATE
FROM SHD_TEACHER
WHERE TEACHERID = NEW.TEACHER_ID
) * UNITS
Any help please?
thanks
using your syntax, I would expect a delimiter statement and a begin/end block. So, try this:
DELIMITER $$
CREATE TRIGGER RATE_PER_UNIT_1
BEFORE INSERT ON SHD_SCHEDULE
FOR EACH ROW
BEGIN
SET NEW.RATE_PER_UNIT =
(
SELECT RATE
FROM SHD_TEACHER t
WHERE t.TEACHERID = NEW.TEACHER_ID
LIMIT 1
)
SET NEW.COST = (
SELECT t.RATE
FROM SHD_TEACHER t
WHERE t.TEACHERID = NEW.TEACHER_ID
) * NEW.UNITS
END $$
DELIMITER ;
You have a limit 1 in the first subquery, suggesting that there might be multiple matches. If so, you will get a run-time error in the second. Also, UNITS is just hanging out there, all alone. I assumed it is in the NEW record.
Here is another way to write this:
DELIMITER $$
CREATE TRIGGER RATE_PER_UNIT_1
BEFORE INSERT ON SHD_SCHEDULE
FOR EACH ROW
BEGIN
SELECT NEW.RATE_PER_UNIT := t.RATE, NEW.COST := t.RATE * NEW.UNITS
FROM (SELECT t.*
FROM SHD_TEACHER t
WHERE t.TEACHERID = NEW.TEACHER_ID
LIMIT 1
) t
END $$
DELIMITER ;
I have a table like this
tbl_user
id
user_id
amount
first i want to update a row based on id
$amount = 123; // dyanamic value
$sql = "UPDATE tbl_user SET amount=amount-'$amount' WHERE id='$id' LIMIT 1 ";
now i want to get updated value of amount column i have applied this sql
$sql = "SELECT amount FROM tbl_user WHERE id='$id' LIMIT 1 ";
my question is can i combine both of above sql or any single query to achieve above task?
The best you could imitate is to use two lines of queries, probably using a variable like:
UPDATE tbl_user SET
amount = #amount := amount-'$amount'
WHERE id='$id' LIMIT 1;
SELECT #amount;
The best you could do then is to create a Stored Procedure like:
DELIMITER //
CREATE PROCEDURE `return_amount` ()
BEGIN
UPDATE tbl_user SET
amount = #amount := amount-'$amount'
WHERE id='$id' LIMIT 1;
SELECT #amount;
END //
And then call Stored Procedure in your PHP.
Note: PostgreSQL has this kind of option using RETURNING statement that would look like this:
UPDATE tbl_user SET amount=amount-'$amount'
WHERE id='$id' LIMIT 1
RETURNING amount
See here
A function can do this easily. It sounds like you want to limit how many times your code connects to the database. With a stored function or procedure, you are only making one connection. Yes, the stored function has two queries inside it (update then select), but these are executed on the server side without stopping to do round trips to the client.
http://sqlfiddle.com/#!2/0e6a09/1/0
Here's my skeleton of your table:
CREATE TABLE tbl_user (
id VARCHAR(100) PRIMARY KEY,
user_id VARCHAR(100),
amount DECIMAL(17,4) );
INSERT INTO tbl_user VALUES ('1', 'John', '100.00');
And the proposed function:
CREATE FUNCTION incrementAmount
(p_id VARCHAR(100), p_amount DECIMAL(17,4))
RETURNS DECIMAL(17,4)
BEGIN
UPDATE tbl_user
SET amount = amount + p_amount
WHERE id = p_id;
RETURN (SELECT amount FROM tbl_user WHERE id = p_id);
END
//
Then you just run one query, a SELECT on the function you just created:
SELECT incrementAmount('1', 5.00)
The query result is:
105
It is not possible with a single query, but you can combine multiple commands into a script and execute them with a single request to the database server.
Run this script:
"UPDATE tbl_user SET amount=amount-'$amount' WHERE id='".$id."';SELECT amount FROM tbl_user WHERE id='".$id."'; "
Also, you might want to check whether $id is a number, as I do not see a protection against SQL injection inside your code. SQL injection is a serious threat, you would do better to prepare and protect yourself against it.
We can also use:
UPDATE tbl_user SET id = LAST_INSERT_ID(id), amount = 2.4,user_id=4 WHERE id = 123;
// SELECT
$id =SELECT LAST_INSERT_ID();
SELECT amount,user_id FROM tbl_user WHERE id = $id LIMIT 1
Here would be the procedure
CREATE PROCEDURE UpdateAndSelect
(
#amount MONEY,
#id INT
)
AS
BEGIN
UPDATE tbl_user
SET amount = #amount
WHERE id = #id
LIMIT 1
SELECT amount
FROM tbl_user
WHERE id = #id
LIMIT 1
END
GO
You would call this stored procedure by setting your variables (#amoutn and #id) and then calling:
exec UpdateAndSelect
Hope this helps solve your problem
IF (( SELECT param FROM changes WHERE type = 'uptime' AND website_id = 1 ORDER BY timestamp DESC LIMIT 1 ) != 'up' )
INSERT INTO changes ( website_id, timestamp, type, param ) VALUES ( 1, NOW(), 'uptime', 'up' )
END IF;
This appears to be an incorrect syntax. How else can I make this work in a single query?
Why are you reading param record outside the query using IF instead of just adding it in the WHERE Condition? If you do it like this then you can just Insert the complete query, if the query returns something your data will be inserted, if your query returns nothing then nothing would be inserted:
INSERT INTO changes ( website_id, timestamp, type, param )
SELECT 1, NOW(), 'uptime', 'up'
FROM changes
WHERE type = 'uptime' AND website_id = 1 AND param != 'up' LIMIT 1
changes seems to be a table for logging events. Given all the variations of INSERTit is not possible to do it. You can try using STORED PROCEDURE to achieve it. You can do something like following:
select param into #last_param from changes where website_id = 1 and type = 'uptime' limit 1;
Now #last_param will contain up or down. In the next statement can be conditional on if last_param is up or down.
Suppose:
$sql = " SELECT * FROM `artwork` WHERE approved = '1' ";
if($filter) $sql .= " AND $filter = '$filter_value' ";
$sql .= " ORDER BY subdate DESC, id DESC
LIMIT 30,30";
If I were to introduce a starting point (eg. WHERE id > 50) and that stipulation affected my LIMIT such that it only returned 10 results. I want 30 results, remember. Is there a way to start from record 1 and continue the selection?
edit: I realize I'm asking for id > 50 in this example and most certainly the first record if we were to rewind would have a lower ID. In my scenario that's okay.
Thanks, Jason.
If there are 100 records and you're
only selecting 10 rows (#90 - #100),
you want to get 20 more rows (#1 - #20)
If those are your constraints, I don't think you will be able to get the desired result set from a single query.
Here's a stored procedure which creates a temp table to get the desired result:
DELIMITER //
DROP PROCEDURE IF EXISTS TMP_TABLE_ARTWORK//
CREATE PROCEDURE TMP_TABLE_ARTWORK (_offset INT, _count INT)
BEGIN
DECLARE res_total INT DEFAULT 0;
SELECT COUNT(*) INTO res_total FROM artwork;
CREATE TEMPORARY TABLE IF NOT EXISTS artwork_tmp ( t_pseudo INT, t_old INT, t_subdate DATETIME );
INSERT INTO artwork_tmp ( t_pseudo, t_old, t_subdate ) SELECT artwork.id, artwork.id, artwork.subdate FROM artwork ORDER BY artwork.subdate DESC;
INSERT INTO artwork_tmp ( t_pseudo, t_old, t_subdate ) SELECT ( artwork.id + res_total ), artwork.id, artwork.subdate FROM artwork ORDER BY artwork.subdate DESC;
PREPARE STMT FROM "SELECT * FROM artwork_tmp ORDER BY t_pseudo LIMIT ?,?";
SET #offset = _offset;
SET #count = _count;
EXECUTE STMT USING #offset, #count;
DROP TABLE artwork_tmp;
END //
DELIMITER ;
You'll probably need to modify it to get it to do what you want (and apparently the prepared statement workaround is no longer required if you're running a newer version of MySQL).
If I understand your question.
You should use LIMIT 0, 30 to get first 30 records which match your query.