Multiple LIKE Conditions in the same column - python-3.x

I am trying to return a query that when returns all the courses associated with a course code for example 'CSC' will give me a tuple of [('CSCA08H3F',), ('CSCA20H3F',), ('CSCA67H3F',)]...etc. I know I have to use the LIKE clause, but I seem to be doing it wrong as well feel like there is a simpler way of doing this lol...
def create_course_table(db, course_file):
'''Courses Table should be ID,Course,Section,Name'''
con = sqlite3.connect(db)
cur = con. cursor()
cur.execute('''DROP TABLE IF EXISTS Courses''')
# create the table
cur.execute('''CREATE TABLE Courses( ID TEXT , Course TEXT ,
Sections TEXT , Name TEXT)''')
# Read CSV File
csv_reader = open(course_file, 'r')
csv_reader.readline()
# Insert the rows
for line in csv_reader:
course = line.strip().split(',')
ID = course[0]
Course = course[1]
Section = course[2]
Name = course[3:]
for names in Name:
cur.execute('''INSERT INTO Courses VALUES (?, ?, ?, ?)''',
(ID, Course, Section, names))
# commit and close the cursor and connection
con.commit()
cur.close()
con.close()
db = 'exams.db'
def find_dept_courses(db, dept):
'''Return the courses from the given department. Use the "LIKE"
clause in your SQL query for the course name.'''
return run_query(db, ''' SELECT Course FROM Courses WHERE LIKE Course 'ACT%'
OR LIKE Course 'AFS%' OR LIKE Course 'ANT%' OR LIKE Course 'AST%'
OR LIKE Course 'BIO%'
OR LIKE Course 'CHM%' OR LIKE Course CIT%' OR LIKE Course 'CLA%'
OR LIKE Course 'CRT%' OR LIKE Course 'CSC%' OR LIKE Course 'CTL%'
OR LIKE Course 'ECT%' OR LIKE Course 'EES%' OR LIKE Course 'ENG%'
OR LIKE Course 'EST%' OR LIKE Course 'FRE%' OR LIKE Course 'FST%'
OR LIKE Course 'GAS%'
OR LIKE Course 'GGR%' OR LIKE Course 'HIS%' OR LIKE Course 'HLT%'
OR LIKE Course 'IDS%' OR LIKE Course 'JOU%' OR LIKE Course 'LGG%'
OR LIKE Course 'LIN%' OR LIKE Course 'MAT%' OR LIKE Course 'MDS%'
OR LIKE Course 'MGA%' OR LIKE Course'MGE%' OR LIKE Course 'MGF%'
OR LIKE Course 'MGH%' OR LIKE Course 'MGI%' OR LIKE Course 'MGM%'
OR LIKE Course 'MGO%' OR LIKE Course 'MGS%' OR LIKE Course 'MGT%'
OR LIKE Course 'NRO%' OR LIKE Course 'PHL%' OR LIKE Course 'PHY%'
OR LIKE Course 'PLI%' OR LIKE Course 'POL%' OR LIKE Course 'PPG%'
OR LIKE Course 'PSC%' OR LIKE Course 'PSY%' OR LIKE Course 'RLG%'
OR LIKE Course 'SOC%' OR LIKE Course 'STA%' OR LIKE Course 'VPA%'
OR LIKE Course 'VPD%' OR LIKE Course 'VPM%' OR LIKE Course 'WST%' AND WHERE Course = ? ''', [dept])
Any help or comments would be appreciated.

Familiarize yourself with the proper syntax of the LIKE clause.
You've put the column name after "LIKE". Column name comes before "LIKE".
The following query will return the Course column from all rows in Courses where the Course column starts with the given string.
SELECT Course FROM Courses WHERE Course LIKE ? || "%";
Substitute ? with the desired prefix.

Since all Course column items are uppercase, then you could use IN instead of LIKE.
Simple test at a prompt that shows that printf used on Course can trim it down to 3 characters and so you can compare to 3 characters of each item to search.
sqlite> .schema
CREATE TABLE test (one text);
sqlite> select * from test;
abcd
efgh
ijkl
abcd
efgh
ijkl
abcd
efgh
ijkl
sqlite> select one from test where printf('%.3s',one) in ('abc');
abcd
abcd
abcd
sqlite>
Thus find_dept_courses() could use:
def find_dept_courses(db, dept):
'''Return the courses from the given department. Use the "IN"
clause in your SQL query for the course name.'''
return run_query(db, ''' SELECT Course FROM Courses WHERE printf('%.3',Course)
IN ('ACT','AFS','ANT','AST','BIO','CHM','CIT','CLA','CRT','CSC','CTL',
'ECT','EES','ENG','EST','FRE','FST','GAS','GGR','HIS','HLT','IDS','JOU',
'LGG','LIN','MAT','MDS','MGA','MGE','MGF','MGH','MGI','MGM','MGO','MGS',
'MGT','NRO','PHL','PHY','PLI','POL','PPG','PSC','PSY','RLG','SOC','STA',
'VPA','VPD','VPM','WST') AND WHERE Course = ? ''', [dept])
Edit: If needed sqlite has a upper() and lower() functions to force the case.
sqlite upper function

Related

MySQL Connector SQL Query using LIKE

I have two sets of similar codes that gives different output. The first example does not return any output but the second example returns a output using the same search input.
First Example:
sql = "SELECT accessionID, title, ISBN, publisher, publicationYear FROM Books WHERE %s LIKE %s";
cursor.execute(sql,(col, "%" + values + "%",))
Second Example:
sql = "SELECT accessionID, title, ISBN, publisher, publicationYear FROM Books WHERE title LIKE %s";
cursor.execute(sql,("%" + values + "%",))
The codes that I am trying to code out is that WHERE is dynamic that depends on which text field user searches on. For example, if a user searches something on the title text box, it will only look into Title.
Another way I could think of is to use If conditions to hardcode, but it only works for the first If conditions and subsequent one does not work.
My question is how to make the SQL line dynamic (using first example) in the sense that I can do two %s in the SQL query line and still get the same output?

How to remove all characters before a specific character in Cognos Report Studio 10.2

I have columns with different company names. In front of each company name there is a Company_ID. After the Company_ID a specific character = _ divides the ID from the Name. For example i have
111_Mercedes
11B4324_Apple
38A_Google
A1ZH8_Airline
I would like to remove all characters including the specific character.
Result should be
Mercedes
Apple
Google
Airline
Thanks in advance
If this is all in one data item and you need a pattern removed, try this:
As an example, 111_Mercedes 11B4324_Apple 38A_Google
The name starts with _ and ends with a space
Because of this, we can use the replace function to set up the process in two steps
1) Wrap the undesired portion in brackets
Sql would look like this
select
concat('<',replace(
replace('111_Mercedes 11B4324_Apple 38A_Google',' ','<')
,'_','>'))
FROM sysibm.sysdummy1
The result would look like
<111>Mercedes<11B4324>Apple<38A>Google
2) Then remove the content in the brackets
Sql would look like this:
Select trim(REGEXP_REPLACE(
'<111>Mercedes<11B4324>Apple<38A>Google'
, '<(.*?)>',' ',1,0,'c'))
FROM sysibm.sysdummy1
The result would look like this
Mercedes Apple Google
For Cognos try to use the functions in the data item definitions
BracketCompany = concat('<',replace(replace([Company ID],' ','<'),'_','>'))
Then another data item over this, to remove the content within the brackets
FinalCompany = trim(REGEXP_REPLACE([BracketCompany], '<(.*?)>',' ',1,0,'c'))

knex.raw with existing columns array using .first statement

Here is existing code:
knex("products")
.first("id", "name", "ingredients")
...
So, currently it just uses array of column names.
Now I want to add calculated column here. It would consists of "constant" + product.id.
For product with id 1 it would be "api/v1/img/1".
For product with id 222 it would be "api/v1/img/222".
Alias of it should be "image".
I have to use knex.raw somehow. Do not understand how and what is the correct syntax to use it with .first().
I'm sorry, I'm unable to understand the question. What kind of result are you trying to achieve? maybe something like this?
knex("products")
.select('*', knex.raw(`'api/v1/img' || ?? as computed`, ['products.id']))
.first()
Like this: https://runkit.com/embed/9okme0czge8z

Find a string using PHPMyAdmin

i have table in DB = dle_post and a row contains id,full_story i want to check if full_story starts with "1." then list its id but the big problem is there are some spaces in the start of full_story some time 1 some time 2 and some time 3 , how can i list all ids starting with "1."
You want to execute some SQL like this, which you can also do in PHPmyAdmin...
SELECT id FROM dle_post WHERE LTRIM(full_story) LIKE '1%';
I think this will work!
Would this query help:
$id = fetch id here;
mysql_query("SELECT * FROM YOUR_TABLE WHERE id LIKE '%".$id."`%'", $someconnection);
YOUR_TABLE -> replace it with your table nime

MYSQL: Using GROUP BY with string literals

I have the following table with these columns:
shortName, fullName, ChangelistCount
Is there a way to group them by a string literal within their fullName? The fullname represents file directories, so I would like to display results for certain parent folders instead of the individual files.
I tried something along the lines of:
GROUP BY fullName like "%/testFolder/%" AND fullName like "%/testFolder2/%"
However it only really groups by the first match....
Thanks!
Perhaps you want something like:
GROUP BY IF(fullName LIKE '%/testfolder/%', 1, IF(fullName LIKE '%/testfolder2/%', 2, 3))
The key idea to understand is that an expression like fullName LIKE foo AND fullName LIKE bar is that the entire expression will necessarily evaluate to either TRUE or FALSE, so you can only get two total groups out of that.
Using an IF expression to return one of several different values will let you get more groups.
Keep in mind that this will not be particularly fast. If you have a very large dataset, you should explore other ways of storing the data that will not require LIKE comparisons to do the grouping.
You'd have to use a subquery to derive the column values you'd like to ultimately group on:
FROM (SELECT SUBSTR(fullname, ?)AS derived_column
FROM YOUR_TABLE ) x
GROUP BY x.derived_column
Either use when/then conditions or Have another temporary table containing all the matches you wish to find and group. Sample from my database.
Here I wanted to group all users based on their cities which was inside address field.
SELECT ut.* , c.city, ua.*
FROM `user_tracking` AS ut
LEFT JOIN cities AS c ON ut.place_name LIKE CONCAT( "%", c.city, "%" )
LEFT JOIN users_auth AS ua ON ua.id = ut.user_id

Resources