Say I have a table called People with columns PersonID and Name and I can select a Person's Name like:
SELECT Name FROM People WHERE PersonID = 1
which for this example will return 'John'.
I also have another table called ForumPosts with the fields ForumPostID and PostContent where PostContent is just TEXT which for the purpose of this example can be something like "My Name is John" or "John likes football"
Now I want to perform a Query which based on a given initial PersonID will return all rows from ForumPosts where the Person's Name matches a word contained in the PostContent field.
A regex which will match single words (or in this case the person's name) is:
[[:<:]]*Person'sNameHere*[[:>:]]
So ideally I want my SQL logic to be something like:
Select * FROM ForumPosts WHERE PostContent
REGEX [[:<:]](SELECT Name FROM People WHERE PersonID = '1') [[:>:]]
However I am not sure if this is even possible or how I would structure the query.
Sounds like you want to create a regex dynamically. Regexes are just strings in MySQL, so you can just use CONCAT to create the string you want.
SELECT *
FROM ForumPosts
WHERE PostContent
REGEXP CONCAT('[[:<:]]',(SELECT Name FROM People WHERE PersonID = '1'),'[[:>:]]')
Even better, you can use a JOIN instead of a subquery
SELECT ForumPosts.*
FROM ForumPosts
JOIN People ON PersonID = 1
WHERE PostContent REGEXP CONCAT('[[:<:]]',People.Name,'[[:>:]]')
DEMO: http://sqlfiddle.com/#!2/40828/1
You can implement this logic using an exists subquery. If I understand your logic correctly:
select fp.*
from ForumPosts fp
where exists (select 1
from people p
where personid = '1' and
fp.PostContent regex concat('[[:<:]]', name, '[[:>:]]')
)
Related
I have a teachers table that looks like this:
teacherid
teacherfname
teacherlname
salary
1
Alexander
Bennett
55.30
I would like to return any record that contains a given string in the teacherfname, teacherlname and salary columns.
What I have right now (this returns exact match only):
SELECT * FROM `teachers` WHERE 'Alexander' IN (teacherfname, teacherlname, salary)
What I would like to do is something like this (this would not return anything):
SELECT * FROM `teachers` WHERE '%Alex%' IN (teacherfname, teacherlname, salary)
What do I need to make the query work? Thank you.
I would assume that the value %Alex% won't ever match the salary column. If you want to search for any rows where the first name or last name include "Alex" I would use simple pattern matching, and force all comparisons to use the same letter case.
For example:
SELECT *
FROM `teachers`
WHERE lower(teacherfname) like '%alex%'
or lower(teacherlname) like '%alex%'
My table name is student and column name is FullName.
Can anyone help with this question? I have tried:
select FullName from student where fullName like "e"
But this is returning 0 rows.
If you want students that contain at leas one 'e', then:
select fullname
from student
where fullname like '%e%'
Note the use of the wildcard character (%) around the e, which searches for the character anywhere in the string.
But if you really mean students that contain a single e (not more, not less), then you need to filter out names that contain more than one. For this, you can do:
select fullname
from student
where fullname like '%e%' and fullname not like '%e%e%'
You could also use replace() and char_length():
select fullname
from student
where char_length(replace(fullname, 'e', '')) = char_length(fullname) - 1
You can use a regular expression:
select fullname
from student
where fullname regexp '^[^e]*e[^e]*$'
i want some correction here. i want to select all people with name fred in database
Here's my query:
SELECT * FROM tdble WHERE CONCAT(name) LIKE CONCAT('%', REPLACE('fred', '')'%')
What you are asking can be simply achieved by either using the "=" operator of the wildcard operator "like" statement.
If you wish to find all records that have an exact match to the name 'Fred' then you should model your query as so:
Select * From tdble Where Name = 'fred'
However, if you want to get all results where the names have 'fred' included in it somewhere use the wildcard operator.
Select * From tdble Where Name like '%fred%'
Also you can further model your query to know where exactly in which form you want 'fred' to appear. Example if you want 'Fred' to be as the last characters of your name string, for instance you wish to get names which ends with fred then model your query like this:
Select * From tdble Where Name like '%fred'
(you will get results like 'alfred', provided there is an alfred in your table)
However if you wish to get all names that begin with fred, model the query like this:
Select * From tdble Where Name like 'fred%'
(you will get results like 'fredinane', provided there is a fredinane in your table)
Cheers
If you want to fetch record with name 'fred', you can simply do Select * from TableName Where Name = 'fred'.
If you want to fetch records which their names' string contain 'fred', you have to use select * from TableName where Name like '%fred%'
I am using rails-4.2.1 and is trying to fetch data from two tables subjects and elective_subjects table in a single query. As rails 4 does not support UNION , I wrote a raw sql query. I want to search by name in both tables. My code is given below
query = "(SELECT id as id, name as name, reference as reference from subjects where name like '#{search}') UNION (SELECT id as id, name as name, null as reference from elective_subjects where name like '#{search}')"
#subjects = ActiveRecord::Base.connection.execute(query)
It is working but when I provide ' in my search the query breaks. So how can I make it a prepared statement. So that sql injection can be avoided
This question is super old and no cares anymore, but I think it is a valid question, so here's the answer:
query = "(SELECT id as id, name as name, reference as reference from subjects where name like $1)
UNION
(SELECT id as id, name as name, null as reference from elective_subjects where name like $1)"
binds = [ActiveRecord::Relation::QueryAttribute.new('name', search, ActiveRecord::Type::Text.new)]
result = ApplicationRecord.connection.exec_query(query, 'SQL', binds, prepare: true)
#subjects = result.rows
That's how you create and use a prepared statement in rails.
I have solved the issue by escaping the search string using following statement.
search = Mysql2::Client.escape(search)
SELECT *
FROM customers
WHERE Firstname LIKE 'George'
The problem is that i have more than 1 rows in the table with tha name Geoge and the result of the query shows only one row
You will want to include the wildcard % character to include the rows the have George present in the name:
SELECT *
FROM customers
WHERE Firstname LIKE '%George%';
If George will always appear at the beginning, then you can include the wildcard on the end:
SELECT *
FROM customers
WHERE Firstname LIKE 'George%';
you need to add a wildcard character % to match any value that contains george
SELECT *
FROM customers
WHERE Firstname LIKE '%George%'
MySQL LIKE Operator
the statement
WHERE Firstname LIKE 'George'
is equivalent with
WHERE Firstname = 'George'
that is why you are only getting one record which firstname is george.
UPDATE 1
SQLFiddle Demo
try
LOWER(Firstname) LIKE '%george%'
handles partial values and avoids case sensietivity issues.