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
Related
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
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);
My database is PostgreSQL. The language is Java.
Table name is phrase with column name name.
At any time many users are inserting many rows to this table.
And we need to make sure that a certain field is unique.
And if such a field was found during loading, I want to return the row ID.
I could for example make a field the unique primary key, and when a row id inserted, catch the exception and look up the existing row.
But I think that is a bad idea.
I could just look for that row first and then insert.
But how can we avoid that the concurrent transactions get in each other's way?
And when downloading, is it better to do a batch download, and how do I do that in PostgreSQL? I do not even know.
You could create a UNIQUE constraint and INSERT ... ON CONFLICT:
CREATE TABLE mytable (
id integer PRIMARY KEY,
name text NOT NULL
CONSTRAINT name_unique UNIQUE
);
INSERT INTO mytable (id, name)
VALUES (1, 'me');
Now to run a batch INSERT that returns the id of each affecte row, run
INSERT INTO mytable (id, name)
VALUES (2, 'me'),
(3, 'new')
ON CONFLICT (name)
DO UPDATE SET name = EXCLUDED.name
RETURNING id;
The strange UPDATE that does not actually change the row is necessary if you want the id back.
Instead of catching the exception, you can use the INSERT ... ON CONFLICT DO NOTHING clause available in PostgreSQL. By checking the number of affected rows (returncode of PreparedStatement.executeUpdate), you can detect if there was a conflict.
E.g.
PreparedStatement pstmt = conn.prepareStatement("insert into x values (?,?) on conflict do nothing");
pstmt.setInt(1, myId);
pstmt.setInt(2, myValue);
int rc = pstmt.executeUpdate();
if (rc == 0) {
// fetch the existing row...
}
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(?);
I have table as follow ::
id || name || Desg || Sal || deptId
1 ||ajay ||MD ||999 ||1
2 ||Kaushal ||Engg ||100 ||2
3 ||Vidhi ||HR ||5000 ||3
4 ||Sonu ||SSP ||200 ||1
5 ||Jay ||Asst Manager ||120 ||3
6 ||Uvi ||Utra ||450 ||5
id is primary column. This is just one table with name person.
I want to get the values of primary key column (here id).
My java method will receives the table name & where clause and will return the ArrayList of values of primary Column. Now the problem is that based on table name it should be decided which column is primary column. Is there any query which can give values ::
<<Part of Query to get values of primary column key>> where sal > 150 & deptId != 1 (Where clause that method will receive)
Database metadata can be extracted from the INFORMATION_SCHEMA tables, as documented here.
I think the table you'd be looking at would be columns:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '<<your schema name>>'
AND TABLE_NAME = '<<your table name>>'
AND COLUMN_KEY = 'PRI'
although that's only for a simplistic case.
For proper index analysis, the statistics table can be consulted. From (somewhat vague) memory, the index name or type can be used to figure out if the index is a primary key index.
Once you have the primary key column name, you can simply construct another query based on that.
In other words (untested):
String prim_colm = getPrimaryKeyColumn (tableName);
String newQuery = "select " + prim_colm + " from " + tableName";
then execute newQuery.
To answer the second part of your question
<<Part of Query to get values of primary column key>>
use...
SELECT <column name> FROM <table name> WHERE....
Where <column name>/<table name> comes from where ever you decide to work it out. Querying database meta data or just using a switch.