I have an SQLite database. I am trying to insert values (users_id, lessoninfo_id) in table bookmarks, only if both do not exist before in a row.
INSERT INTO bookmarks(users_id,lessoninfo_id)
VALUES(
(SELECT _id FROM Users WHERE User='"+$('#user_lesson').html()+"'),
(SELECT _id FROM lessoninfo
WHERE Lesson="+lesson_no+" AND cast(starttime AS int)="+Math.floor(result_set.rows.item(markerCount-1).starttime)+")
WHERE NOT EXISTS (
SELECT users_id,lessoninfo_id from bookmarks
WHERE users_id=(SELECT _id FROM Users
WHERE User='"+$('#user_lesson').html()+"') AND lessoninfo_id=(
SELECT _id FROM lessoninfo
WHERE Lesson="+lesson_no+")))
This gives an error saying:
db error near where syntax.
If you never want to have duplicates, you should declare this as a table constraint:
CREATE TABLE bookmarks(
users_id INTEGER,
lessoninfo_id INTEGER,
UNIQUE(users_id, lessoninfo_id)
);
(A primary key over both columns would have the same effect.)
It is then possible to tell the database that you want to silently ignore records that would violate such a constraint:
INSERT OR IGNORE INTO bookmarks(users_id, lessoninfo_id) VALUES(123, 456)
If you have a table called memos that has two columns id and text you should be able to do like this:
INSERT INTO memos(id,text)
SELECT 5, 'text to insert'
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');
If a record already contains a row where text is equal to 'text to insert' and id is equal to 5, then the insert operation will be ignored.
I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.
I would advice that you instead design your table so that no duplicates are allowed as explained in #CLs answer below.
For a unique column, use this:
INSERT OR REPLACE INTO tableName (...) values(...);
For more information, see: sqlite.org/lang_insert
insert into bookmarks (users_id, lessoninfo_id)
select 1, 167
EXCEPT
select user_id, lessoninfo_id
from bookmarks
where user_id=1
and lessoninfo_id=167;
This is the fastest way.
For some other SQL engines, you can use a Dummy table containing 1 record.
e.g:
select 1, 167 from ONE_RECORD_DUMMY_TABLE
Related
I have a query which I am trying to test. The query should update the data if it finds data in the table with existing primary key. If it doesn't then insert into the table.
The Primary key is of type int and in the properties I can see Identity is set to "True" which I assume it means that it will automatically set the new id for the primary if it is inserted.
MERGE INTO Test_table t
USING (SELECT 461232 ID,'Test1-data' Fascia FROM Test_table) s
ON (t.ID = s.ID)
WHEN MATCHED THEN
UPDATE SET t.Fascia = s.Fascia
WHEN NOT MATCHED THEN
INSERT (Fascia)
VALUES (s.Fascia);
The issue here is this query doesn't work and it never inserts the data or updates. Also, query gets compiled and I don't get any compilation error
Also the reason I want this query is to work because then I will use Java prepared statement to query the database so I am assuming I can do
SELECT ? ID,? Fascia FROM Test_table
So that I can pass the values with set methods in java.
Please let me know if there is something wrong in my query.
You are selecting from the target table as your source.
You either need to remove your FROM Test_table or have at least 1 row in Test_table prior to your merge.
rextester demo: http://rextester.com/XROJD28508
MERGE INTO Test_table t
USING (SELECT 461232 ID,'Test1-data' Fascia --FROM Test_table
) s
ON (t.ID = s.ID)
WHEN MATCHED THEN
UPDATE SET t.Fascia = s.Fascia
WHEN NOT MATCHED THEN
INSERT (Fascia)
VALUES (s.Fascia);
I am wanting to insert some data into a MySQL table, these are the columns:
uuid | id_1 | id_41
the "id_1" and "id_41" could be anything, all I know is the primary key (uuid) and I am wanting to be able to insert into the table while only knowing the uuid column value as I am doing this so far:
PreparedStatement newPlayer = "INSERT INTO `test` values(?);";
newPlayer.setString(1, event.getPlayer().getUniqueId().toString());
But when I test it, it doesn't add to the table and does not produce any errors. I also know that all of the other values have a default value of 0
If you want to add a row without all columns included, you need to specify the column's name
INSERT INTO `test` (`uuid`) values(?);
Simple tell to insert the column you want insert eg for uuid
INSERT INTO `test` ( `uuid`) values(?);
This is my code with 1 FK.
here's the columns
([PK]charityRoomID, charityRoomStatus, [FK]charityWardID)
INSERT INTO tbl_addcharityroom1 (charityRoomStatus, charityWardID)
VALUES ('"+jTextField10aw.getText() +"', (
select charityWardID
from tbl_addcharityward
where diseaseCategory='"+ jComboBox1.getSelectedItem().toString() +"'))";
Now, I added a new column(RateID) which is another FK, but i don't know the correct statement for multiple FK. here's the columns
([PK]charityWardID, charityRoomStatus, [FK]charityWardID, [FK]rateID)
I am using netbeans & mySQL
A FK is just a constraint on a database column. It basically means that your column content must map to a specified column when you insert data.
So, if your insert statement specifies a value that exist in the ID column of your Rate table, everything will be allright. Otherwise, an exception will occur.
Basically you just need to do this, replacing "yourRateIdValue" by an Id that actually exist in your Rate table:
"INSERT INTO tbl_addcharityroom1 (charityRoomStatus, charityWardID, rateID)
VALUES ('" + jTextField10aw.getText() + "', (
select charityWardID
from tbl_addcharityward
where diseaseCategory='"+ jComboBox1.getSelectedItem().toString() +"'), yourRateIdValue)";
You can also replace the "yourRateIdValue" by a select statement, as you did for the "charityWardID" column
I am trying to create (java-based) messaging webapp. The messages are stored using MySQL using three tables:
'messages': has two columns, an id primary key ('idmessage') and the message ('message').
'tags': The user also inputs a tag associated with their message. This has two columns - the tag (which is also a primary key) and a count ('count').
'message_tag_link': Since there is a many-to-one relationship between messages and tags I have a third link table. This has two columns, both foreign keys to the messages ('fk_idmessage') and tags tables’ ids ('fk_tag').
Inserting messages into the database works fine. I use these following lines in Java:
pst1 = connection.prepareStatement("INSERT INTO messages(message) VALUES (?)");
pst2 = connection.prepareStatement("INSERT INTO tags(tag,count) VALUES (?,1) ON DUPLICATE KEY UPDATE count = count + 1");
pst3 = connection.prepareStatement("INSERT INTO message_tag_link(fk_idmessage,fk_tag) VALUES (? , ?)");
As can be seen ‘count’ increments in pst2 every time a duplicate tag entry is made.
I am trying to work out how to fully delete a message. I have the on delete cascade description on my foreign keys in my link table’s columns but am not sure what to do next. For a given 'messageid' I need to:
Delete a row in 'messages' table
Delete the associated row in the 'message_tag_link' table
Decrement the count value in the 'tags' table when a message deletion is successful, or delete this row entirely if count becomes zero.
Is it possible to do all this within MySQL using a Java PreparedStatement? Any pointers much appreciated. I am a total MySQL novice, so please be kind!
These queries should do what you need. ? in each query should be the message id that is to be deleted
//Update count
UPDATE tags SET `count` = `count` - 1 WHERE tag_id IN (SELECT fk_tag FROM message_tag_link WHERE fk_idMessage = ?);
//Remove link
DELETE FROM message_tag_link WHERE fk_idmessage = ?;
DELETE FROM messages WHERE id = ?;
//Remove unused tags
DELETE FROM tags WHERE `count` = 0;
As you've found out however maintaining a count can be annoying. Better is to use the link itself.
SELECT COUNT(fk_idmessage) AS msgcount FROM message_tag_link WHERE fk_tag = ?;
Also you can add a CASCADE so that when messages are deleted the tag link gets deleted too (see here). Be careful with this behavior however).
This solution still leaves tags with no messages but you can remove these using the query:
DELETE FROM tags t WHERE NOT EXISTS (SELECT 1 FROM nessage_tag_link WHERE t.tag_id = fk_tag)
I want to get the primary key column value for the rows which were affected by query in Java. I am using MySql DB. Suppose query is like,
update user set pincode = 390023 where area like '%ABC Road%'
Then in java, I want the ids of each row (Primary key of each row) updated. Something that can be possible with Statement object in Java may be.
Select the rows just before you update them.
Use select id from user where area like '%ABC Road%'.
Remember to enclose those two operations in transaction to avoid row changes between those two.
SELECT id FROM user WHERE area LIKE '%ABC Road%';
or alternative way:
SET #ids = NULL;
UPDATE user
SET pincode = 390023
WHERE area LIKE '%ABC Road%'
AND (SELECT #ids := CONCAT_WS(',', id, #ids));
SELECT #ids;