SQL Insert statement where single value selects from another table - sql

I have the following SQL:
INSERT INTO Invite VALUES (NULL,?,(SELECT id FROM User WHERE name = ?),?);
However this doesnt seem to work.
Can anyone tell me what i am doing wrong?
Update
The following php code gives me erro code 1136:
$sql = 'INSERT INTO Invite SELECT NULL, ?, id, ? FROM User WHERE username = ?';
$variables = array($team_id,$_SESSION['User']['id'],$username);
$result = $this->db->prepTemplate($sql, 'iis', $variables);

INSERT INTO Invite
SELECT NULL, ?, id, ?
FROM User
WHERE name = ?

Related

Update or add value with id

I am just learning SQLDelight and was hoping to find how to add an object with an ID if it doesn't exist already if it does exist then update that current object with the given id.
currently, I am deleting the current object with id, then adding an object and was hoping to reduce this into one simple call.
My current code:
CREATE TABLE Color (
id TEXT NOT NULL,
name TEXT NOT NULL,
hex TEXT NOT NULL
);
getColorWithId:
SELECT * FROM Color
WHERE id = ?;
saveColor:
INSERT OR REPLACE INTO Color (id, name, hex)
VALUES (?, ?, ?);
deleteColorWithId:
DELETE FROM Color
WHERE id = ?;
I was hoping to change it to replace saveColor and deleteColorWithId with something like:
updateColorWithId:
INSERT OR REPLACE INTO Color (id, name, hex)
WHERE id = ?
VALUES (?, ?, ?);
but it doesn't work with this error <insert stmt values real> expected, got 'WHERE'
can anyone help? I can't find anything in the docs.
Your statement saveColor serves as UPSERT command and it works exactly as you wish. You don't need to create another statement.
INSERT OR REPLACE INTO Color (id, name, hex)
VALUES (?, ?, ?);
You must specify PRIMARY KEY on id column and you can use saveColor as updateColorWithId.
You are already there, try something like this:
Check if the record exists. If it does, then update otherwise add a new row. Using named arguments as per documentation would be ideal. https://cashapp.github.io/sqldelight/native_sqlite/query_arguments/
updateOrInsert:
IF EXISTS (SELECT 1 FROM Color WHERE id = :id)
BEGIN
UPDATE Color
SET id = :id,
name = :name,
hex = :hex
WHERE id = :id
END
ELSE
BEGIN
INSERT INTO Color(id, name, hex)
VALUES (:id, :name, :hex);
END
Usage
dbQuery.updateOrInsert(id = BGColor.id, name = bgColor.name, hex = bgColor.hex)
Take a look at this, might be useful REPLACE INTO vs Update

Search ID by : APP_USER apex oracle

I have an authorization table. There's a Username, Login and Password I want. Also I have P1_item, I want to assign this variable Username, when I write a log in log everything works and when the APP_USER. does not work
CREATE TABLE test
(
name varcahar2(10),
login varcahar2(10),
pass NUMBER(10)
);
INSERT INTO test
VALUES ('Andrii', 'log', 111);
select name from test where login = '&APP_USER.'
select name from test where login = 'log'
Don't use &APP_USER. as this is a substitution string - instead, bind the variable directly using :APP_USER, e.g.
select name from test where login = :APP_USER
There is no value "APP_USER" in the login column...
you can use V function (more details), but it is not recommended in SQL:
select name from test where login = V('APP_USER');
or you can bind the variable:
select name from test where login = :APP_USER;

App Script run basic queries using Cloud SQL

I am looking how to create basic queries from Cloud SQL using App Script.
q1: "SELECT id FROM users WHERE name = 'some name';"
q2: "UPDATE users SET name = 'other name' WHERE id = 1;"
q3: "DELETE FROM users WHERE id = 1;"
I can read the entire table and insert data, however i cannot find the documentation on the google docs site for these types of queries.
I have tried using the query filter however it returns a bool not the ID INT, I am looking for.
var id =app.datasources.Users.query.filters.name._equals == "some name";
app.Pages.Page1.decendents.label1.text = id;
:>> Type mismatch: Cannot set type Boolean for property text. Type String is expected
Note: Users table sql equivelent (id INT AUTO_INCREMENT, name VARCHAR(64), PRIMARY KEY(id))
Your query server script syntax is wrong. Try
var query = app.models.Users.newQuery(); //new query
query.filters.name._equals = "some name"; //Note single`=`;
var records = query.run(); //run the query
app.Pages.Page1.decendents.label1.text = records[0].id;
To Read:
Query#run

Using DBI in Perl to update multiple fields in one line?

I'm mediocre with perl and new to SQL, so excuse any lameness.
I've got a perl script I'm working on that interacts with a database to keep track of users on IRC. From tutorials I've found, I've been able to create the db, create a table within, INSERT a new record, UPDATE a field in that record, and SELECT/find records based on a field.
The problem is, I can only figure out how to UPDATE one field at a time and that seems inefficient.
The code to create the table:
my $sql = <<'END_SQL';
CREATE TABLE seenDB (
id INTEGER PRIMARY KEY,
date VARCHAR(10),
time VARCHAR(8),
nick VARCHAR(30) UNIQUE NOT NULL,
rawnick VARCHAR(100),
channel VARCHAR(32),
action VARCHAR(20),
message VARCHAR(380)
)
END_SQL
$dbh->do($sql);
And to insert a record using values I've determined elsewhere:
$dbh->do('INSERT INTO seenDB (nick, rawnick, channel, action, message, date, time) VALUES (?, ?, ?, ?, ?, ?, ?)', undef, $nickString, $rawnickString, $channelString, $actionString, $messageString, $dateString, $timeString);
So, when the script needs to update, I'd like to update all of these fiends at once, but right now the only thing that works is one at a time, using syntax I got from the tutorial:
$dbh->do('UPDATE seenDB SET time = ? WHERE nick = ?',
undef,
$timeString,
$nickString);
I've tried the following syntaxes for multiple fields, but they fail:
$dbh->do('UPDATE seenDB (rawnick, channel, action, message, date, time) VALUES (?, ?, ?, ?, ?, ?)', undef, $rawnickString, $channelString, $actionString, $messageString, $dateString, $timeString);
and
$dbh->do('UPDATE seenDB SET rawnick=$rawnickString channel=$channelString action=$actionString message=$messageString date=$dateString time=$timeString WHERE nick=$nickString');
Is there a better way to do this?
You can update several fields at once in pretty much the same way as you update a single field, just list them comma separated in the update, something like;
$dbh->do('UPDATE seenDB SET rawnick=?, channel=?, action=?, message=?, date=?, time=? WHERE nick=?',
undef,
$rawnickString,
$channelString,
$actionString,
$messageString,
$dateString,
$timeString,
$nickString
);

SQL Select and Delete help

How do you go about selecting or deleting a specific list of numbers from a table?
For example,
select * from Table where ID = 1,2,3,4,5,6
doesn't work. I would have to do where ID = 1 or ID = 2 or ID = 3 etc etc
How do you do you use a comma delineated list to select multiple values using one where clause?
select * from table where ID IN(1,2,3,4,5)
select * from table where ID IN (1,2,3,4,5,6)
Try using the in operator select * from Table where ID in (1,2,3,4,5,6)
works with delete too
you can try with
Where ID in (1,2,3)
if you are looking for dynamic query then
execute ('select * from table where ID IN (1,2,3,4,5,6)')
otherwise
select * from table where ID IN (1,2,3,4,5,6)
will do the job
SELECT * FROM myTable WHERE id BETWEEN 1 AND 6
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
SELECT * FROM Table WHERE Id IN (1,2,3,4,5,6)
Note that you can't insert the entire list in a parametrized query - for example, WHERE Id IN (?) with a parameter containing '1,2,3,4,5,6' will not yield the results you're after.
A nice way to avoid building your SQL string dynamically (and potentially exposing yourself to SQL Injection) is to dynamically build the number of parameters, and then concatenate them into your SQL.
A full example with Python and SQLite (although this method can be used in any language with any SQL database engine):
ids = [1, 2, 3, 4, 5, 6]
params = tuple(ids) # because sqlite wants the parameters in tuple format
paramstring = ', '.join(['?' for dummyp in ids])
# paramstring now contains '?, ?, ?, ?, ?, ?'
# - the same number of '?' as the number of ids
sql = 'SELECT * FROM Table WHERE Id IN (' + paramstring + ')'
# sql now contains 'SELECT * FROM Table WHERE Id IN (?, ?, ?, ?, ?, ?)'
conn = sqlite3.connect(':memory:')
cursor = conn.execute(sql, params)
# You can now iterate through the cursor to get your data