SQL return rows if matches keywords - sql

I have a large list of strings (outside of a PostgreSQL database), and I want to go through that list of strings (in a loop) and want to check to see if any part of the string belongs in a table.
For example, I have the two following tables:
table name: trigger_keyword
id (int)
keyword (text)
and table 2:
table name: trigger_message
id int
message text
trigger_keyword_id int /*this is a fk to id on trigger_keyword */
Let's assume we have key word "weather good" in the trigger_keyword table, and we have a message in trigger_message linked to the id of that keyword.
so below is an example of how things look in our tables
trigger_keyword table
id keyword
-----------------------------------------------------
1 weather good
trigger_message table
id message trigger_keyword_id
-----------------------------------------------------
1 yes, the weather is good 1
in one of our strings outside of the SQL database we have the following sentence
"is the weather good in Alaska?"
What SQL can I write to return "yes, the weather is good" because "weather good" is in our trigger_keyword table? do I need to use LIKE for this? I only need help with the SQL portion.

That sounds like you should use full text search:
SELECT m.message
FROM trigger_keyword AS k
JOIN trigger_message AS m ON k.id = m.trigger_keyword_id
WHERE to_tsvector('english', 'is the weather good in Alaska?')
## phraseto_tsquery('english', k.keyword);

Related

How to display the list of books of a user in php code

I am a beginner in programming.
I want to create a site in which I would like to display the list of books of a user that he has previously added. here is the schema of the code.
table book;
id ,name,detail ,urlimage.
table users;
id,name,email,password.
table add_book;
uses_id INT ,book_id INT , key primary (users_id ,book_id ).
I have three tables in my database; the book table, the users table and the add_book table. their structures is given in the above question add_book.users_id and add_book.book_id are foreign keys. I would like to make sure that when a user adds a book to his list, an entry is created in the add_book table with the request. ('INSERT INTO kal224_sory.add_book (users_id, book_id) VALUES (: users,: book)'); $ sql-> execute (['users' => $ users_id, 'book' => $ book_id]); .It works well where there is problem, I try to send in json the fields of the table book that correspond to book_id which have the same entries users_id where(add_book.users_id = $ users_id) of the table add_book. the code I tried is;
You need to SELECT the data from the add_book table that belongs to a particular uses_id (sp.)
SELECT * FROM add_book WHERE uses_id = 1 -- change '1' to whatever user's ID you'd like to view data for

Specify the format of a string with letters and numbers in triggers SQL

I am actually writing a trigger with Oracle and I want to specify the format of a variable but I'm not finding the proper syntax to do that.
I have a table 'Person' which gathers students and professors and all of them have a matricule. Professors have a "pmatricule" which means a string with "p" followed by a chain of 3 to 6 numbers. Example : p456123
Students have only a matricule with 3 to 7 numbers such as : 1234567
My triggers has to compare the new matricule I want to input in my table 'Person' to check if it respects the format I described.
Has someone the syntax to do such a thing ? I have searched for a long time but my trigger is not working whatever I try.
You can do this with a table level CHECK constraint. You haven't provided a table description so column names are guesses.
alter table person add constraint person_matricule_ck check
( ( person_type = 'PROFESSOR' and regexp_like(matricule, '^p[0-9]{6}$') )
or ( person_type = 'STUDENT' and regexp_like(matricule, '^[0-9]{7}$') )
)
/
We shouldn't use triggers for rules which can be enforced with constraints: constraints are both idiomatic SQL and more efficient.

Is it possible to CREATE TABLE with a column that is a combination of other columns in the same table?

I know that the question is very long and I understand if someone doesn't have the time to read it all, but I really wish there is a way to do this.
I am writing a program that will read the database schema from the database catalog tables and automatically build a basic application with the information extracted from the system catalogs.
Many tables in the database can be just a list of items of the form
CREATE TABLE tablename (id INTEGER PRIMARY KEY, description VARCHAR NOT NULL);
so when a table has a column that references the id of tablename I just resolve the descriptions by querying it from the tablename table, and I display a list in a combo box with the available options.
There are some tables however that cannot directly have a description column, because their description would be a combination of other columns, lets take as an example the most important of those tables in my first application
CREATE TABLE bankaccount (
bankid INTEGER NOT NULL REFERENCES bank,
officeid INTEGER NOT NULL REFERENCES bankoffice,
crc INTEGER NOT NULL,
number BIGINT NOT NULL
);
this as many would know, would be the full account number for a bank account, in my country it's composed as follows
[XXXX][XXXX][XX][XXXXXXXXXX]
^ ^ ^ ^
bank id | crc account number
|
|_ bank office id
so that's the reason of the way my bankaccount table is structured as is.
Now, I would like to have the complete bank account number in a description column so I can display it in the application without giving a special treatment to this situation, since there are some other tables with similar situation, something like
CREATE TABLE bankaccount (
bankid INTEGER NOT NULL REFERENCES bank,
officeid INTEGER NOT NULL REFERENCES bankoffice,
crc INTEGER NOT NULL,
number BIGINT NOT NULL,
description VARCHAR DEFAULT bankid || '-' || officeid || '-' || crc || '-' || number
);
Which of course doesn't work since the following error is raised1
ERROR: cannot use column references in default expression
If there is any different approach that someone can suggest, please feel free to suggest it as an answer.
1 This is the error message given by PostgreSQL.
What you want is to create a view on your table. I'm more familiar with MySQL and SQLite, so excuse the differences. But basically, if you have table 'AccountInfo' you can have a view 'AccountInfoView' which is sort of like a 'stored query' but can be used like a table. You would create it with something like
CREATE VIEW AccountInfoView AS
SELECT *, CONCATENATE(bankid,officeid,crc,number) AS FullAccountNumber
FROM AccountInfo
Another approach is to have an actual FullAccountNumber column in your original table, and create a trigger that sets it any time an insert or update is performed on your table. This is usually less efficient though, as it duplicates storage and takes the performance hit when data are written instead of retrieved. Sometimes that approach can make sense, though.
What actually works, and I believe it's a very elegant solution is to use a function like this one
CREATE FUNCTION description(bankaccount) RETURNS VARCHAR AS $$
SELECT
CONCAT(bankid, '-', officeid, '-', crc, '-', number)
FROM
bankaccount this
WHERE
$1.bankid = this.bankid AND
$1.officeid = this.officeid AND
$1.crc = this.crc AND
$1.number = this.number
$$ LANGUAGE SQL STABLE;
which would then be used like this
SELECT bankaccount.description FROM bankaccount;
and hence, my goal is achieved.
Note: this solution works with PostgreSQL only AFAIK.

Update TAG Relational table from select match on main table with keywords field and tag table with individual keywords

I imported the Software PAD File Database from http://paddatabase.net/download.html into Microsoft Access in a table called main:
MAIN
-----
ID
ProgramName
Keywords
.
.
I created two new tables: Tags and TagSoftwareRel.
Tags
--------
ID
Tag
TagSoftwareRel
--------------
ID
SoftwareID <- (MainTable)
TagID <- tags table
I extracted all the keywords from the field Keywords as individual words in the Tags table. They Keywords field from Main looks like this:
Keywords
Paul, animated, moving monk, paulaner
Image,Imaging,Graphics,Rotate,Resize,Effects,
Sharpen,Blur,JPEG,TIFF,BMP,WBMP,PSD,GIF,PDF,Format,ICM,ICC,CMYK,
thumbnail,Convert,Display,AJAX,AVI,red-eye removal,lossless JPEG transform
correction, rich,internet,applications,ebooks,webmaster,authoring,
What I want to do is create a SQL Query which Inserts the tagID from the tags table into tagsoftwarerel.tagid and the related softwareID from the main table into tagsoftwarerel.softwareid by using a where tags.tag like main.keywords
I'm sort of at loss of where to start with this.
As it is a public DB I can provide a copy of the database to anyone interested.
Any assistance would be most appreciated. Thank you.
I assume that the field ID from the TagSoftwareRel is an autovalue or identity. That means the value is created automaticly by inserting a new row:
I understand that you already filled the Tags-Table.
Here is a query which would fill the TagSoftarerel-Table:
Insert into TagSoftarerel (SoftwareID, TagID)
Select m.Id,
(Select T.TagId from Tag T where T.Tag = m.Keyword) as TagId
from MAIN m
Advice:
I think you could find a better solution. The Tag-information is redundant in your solution.
If you would just add the Tag.Id to the main-table you could get rid of the Keyword column and store the tag-information solely in the tag table, where it belongs to.

Generating Random ID's in Microsoft SQL Server

I want to create a table in sql server and fill it up with data (people's info) every person should have a unique ID different than the auto incremented ID's by sql server
For example i need the ID for the first person inserted like this: 2016xxxx
how to fix the 2016 and randomly generate the numbers after that to be filled instead of xxxx
should i use a regular expression ?
You can also create a computed column like below
CREATE TABLE tableName
(
PkAutoId INT PRIMARY KEY IDENTITY(1,1),
PersonUniqueNo AS (CAST(DATEPART(YEAR,GETDATE()) AS VARCHAR) + RIGHT(RIGHT(CAST(RAND() AS VARCHAR),4) + CAST(PkAutoId AS VARCHAR),4))
)
Computed Column "PersonUniqueNo" is 8 Digit Unique Number comprising of Current Year And Conceited value of Random number and Primary Key Id for 4 Length, Total length will be 8 as asked.
You could create a function that would get the next value for you and use that instead of an AUTO_INCREMENT field.
I wouldn't recommend it tho. You shouldn't format the data like that before inserting it. That sort of thing should be done on the way out, preferably by the front-end code. Or you can just write a query and create a view ...
However if you must do that here is the complete answer with the code:
Is there a way to insert an auto-incremental primary id with a prefix in mysql database?