This should ideally be done with the help of SQL Server full text search if using that.
However, if you can’t get that working on your DB for some reason, here is a performance-intensive solution:
-- table to search in
CREATE TABLE dbo.myTable
(
myTableId int NOT NULL IDENTITY (1, 1),
code varchar(200) NOT NULL,
description varchar(200) NOT NULL -- this column contains the values we are going to search in
) ON [PRIMARY]
GO
-- function to split space separated search string into individual words
CREATE FUNCTION [dbo].[fnSplit] (@StringInput nvarchar(max),
@Delimiter nvarchar(1))
RETURNS @OutputTable TABLE (
id nvarchar(1000)
)
AS
BEGIN
DECLARE @String nvarchar(100);
WHILE LEN(@StringInput) > 0
BEGIN
SET @String = LEFT(@StringInput, ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput) - 1, -1),
LEN(@StringInput)));
SET @StringInput = SUBSTRING(@StringInput, ISNULL(NULLIF(CHARINDEX
(
@Delimiter, @StringInput
),
0
), LEN
(
@StringInput)
)
+ 1, LEN(@StringInput));
INSERT INTO @OutputTable (id)
VALUES (@String);
END;
RETURN;
END;
GO
-- this is the search script which can be optionally converted to a stored procedure /function
declare @search varchar(max) = 'infection upper acute genito'; -- enter your search string here
-- the searched string above should give rows containing the following
-- infection in upper side with acute genitointestinal tract
-- acute infection in upper teeth
-- acute genitointestinal pain
if (len(trim(@search)) = 0) -- if search string is empty, just return records ordered alphabetically
begin
select 1 as Priority ,myTableid, code, Description from myTable order by Description
return;
end
declare @splitTable Table(
wordRank int Identity(1,1), -- individual words are assinged priority order (in order of occurence/position)
word varchar(200)
)
declare @nonWordTable Table( -- table to trim out auxiliary verbs, prepositions etc. from the search
id varchar(200)
)
insert into @nonWordTable values
('of'),
('with'),
('at'),
('in'),
('for'),
('on'),
('by'),
('like'),
('up'),
('off'),
('near'),
('is'),
('are'),
(','),
(':'),
(';')
insert into @splitTable
select id from dbo.fnSplit(@search,' '); -- this function gives you a table with rows containing all the space separated words of the search like in this e.g., the output will be -
-- id
-------------
-- infection
-- upper
-- acute
-- genito
delete s from @splitTable s join @nonWordTable n on s.word = n.id; -- trimming out non-words here
declare @countOfSearchStrings int = (select count(word) from @splitTable); -- count of space separated words for search
declare @highestPriority int = POWER(@countOfSearchStrings,3);
with plainMatches as
(
select myTableid, @highestPriority as Priority from myTable where Description like @search -- exact matches have highest priority
union
select myTableid, @highestPriority-1 as Priority from myTable where Description like @search + '%' -- then with something at the end
union
select myTableid, @highestPriority-2 as Priority from myTable where Description like '%' + @search -- then with something at the beginning
union
select myTableid, @highestPriority-3 as Priority from myTable where Description like '%' + @search + '%' -- then if the word falls somewhere in between
),
splitWordMatches as( -- give each searched word a rank based on its position in the searched string
-- and calculate its char index in the field to search
select myTable.myTableid, (@countOfSearchStrings - s.wordRank) as Priority, s.word,
wordIndex = CHARINDEX(s.word, myTable.Description) from myTable join @splitTable s on myTable.Description like '%'+ s.word + '%'
-- and not exists(select myTableid from plainMatches p where p.myTableId = myTable.myTableId) -- need not look into myTables that have already been found in plainmatches as they are highest ranked
-- this one takes a long time though, so commenting it, will have no impact on the result
),
matchingRowsWithAllWords as (
select myTableid, count(myTableid) as myTableCount from splitWordMatches group by(myTableid) having count(myTableid) = @countOfSearchStrings
)
, -- trim off the CTE here if you don't care about the ordering of words to be considered for priority
wordIndexRatings as( -- reverse the char indexes retrived above so that words occuring earlier have higher weightage
-- and then normalize them to sequential values
select s.myTableid, Priority, word, ROW_NUMBER() over (partition by s.myTableid order by wordindex desc) as comparativeWordIndex
from splitWordMatches s join matchingRowsWithAllWords m on s.myTableId = m.myTableId
)
,
wordIndexSequenceRatings as ( -- need to do this to ensure that if the same set of words from search string is found in two rows,
-- their sequence in the field value is taken into account for higher priority
select w.myTableid, w.word, (w.Priority + w.comparativeWordIndex + coalesce(sequncedPriority ,0)) as Priority
from wordIndexRatings w left join
(
select w1.myTableid, w1.priority, w1.word, w1.comparativeWordIndex, count(w1.myTableid) as sequncedPriority
from wordIndexRatings w1 join wordIndexRatings w2 on w1.myTableId = w2.myTableId and w1.Priority > w2.Priority and w1.comparativeWordIndex>w2.comparativeWordIndex
group by w1.myTableid, w1.priority,w1.word, w1.comparativeWordIndex
)
sequencedPriority on w.myTableId = sequencedPriority.myTableId and w.Priority = sequencedPriority.Priority
),
prioritizedSplitWordMatches as ( -- this calculates the cumulative priority for a field value
select w1.myTableId, sum(w1.Priority) as OverallPriority from wordIndexSequenceRatings w1 join wordIndexSequenceRatings w2 on w1.myTableId = w2.myTableId
where w1.word <> w2.word group by w1.myTableid
),
completeSet as (
select myTableid, priority from plainMatches -- get plain matches which should be highest ranked
union
select myTableid, OverallPriority as priority from prioritizedSplitWordMatches -- get ranked split word matches (which are ordered based on word rank in search string and sequence)
),
maximizedCompleteSet as( -- set the priority of a field value = maximum priority for that field value
select myTableid, max(priority) as Priority from completeSet group by myTableId
)
select priority, myTable.myTableid , code, Description from maximizedCompleteSet m join myTable on m.myTableId = myTable.myTableId
order by Priority desc, Description -- order by priority desc to get highest rated items on top
--offset 0 rows fetch next 50 rows only -- optional paging
method must have a body
This usually means mismatched braces. It can occur when you have one too many braces elsewhere, so the compiler thinks you’re trying to define a method. For example, the following code won’t compile:
public class someClass {
public void method();
}
Double-check the pairings of your open/close curly brackets.
String testString = 'Test';
for (Lead L : Trigger.New){
if(L.Name.Contains(testString))
L.Status = 'Disqualified';
There’s a lot wrong here:
for (Lead L : Trigger.New){
You have an opening {
, but no closing }
. If this was just because you didn’t copy that part, then ignore this part, but I’m pretty sure you’re missing a }
somewhere.
if(L.Name.Contains(testString))
L.Status = 'Disqualified';
This is a trap waiting to happen. Always use {
and }
around the statement for the if statement, even if there’s only one. With some clever indentation and a lack of curly brackets, you can lead yourself into a trap:
if(L.Name.Contains(testString))
L.Status = 'Disqualified';
L.Email = 'invalid-email@example.com';
While you think that both of these statements might only execute if Name contains the string, the truth is, the Email field will always be set, because you forgot the curly brackets. Avoid this trap by getting in the habit:
if(L.Name.Contains(testString)) {
L.Status = 'Disqualified';
L.Email = 'invalid-email@example.com';
}
if(L.Name.Contains(testString)) {
This is a particularly clever trap waiting to happen; the Name field isn’t automatically populated in some situations, like a Before Insert trigger, because it’a compound field. You shouldn’t rely on that field being populated. This is true for Accounts (with Person Accounts), Contacts, and Leads. Other types of objects don’t have that problem.
It’s usually sufficient to just check the LastName, which is always a required field:
if(L.LastName.Contains(testString)) {
Finally, «contains» is case-sensitive. That means I can easily get around your code by writing «test» instead of «Test». For this specific case, consider using containsIgnoreCase:
if(L.LastName.containsIgnoreCase(testString)) {
Finally, keep in mind that you might be filtering out legitimate customers if you do this: the Test clan, of which first migrated to the United States in the 17th century, has many different variations, including:
… Testa, Testi, Testini, Testino, Testoni, Testone, Testai, Testaj, Testani, Testabruna, Testadiferro, Testagrossa, Testaquadra …
You might want to come up with a more elaborate method of filtering out test leads rather than depend on a specific name being entered, such as using a custom field or something else.
For this, you can use the LIKE operator along with CONCAT() function. Let us first create a table −
mysql> create table DemoTable ( Value text ); Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('MySQL'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Is'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Relational'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Database'); Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+ | Value | +------------+ | MySQL | | Is | | Relational | | Database | +------------+ 4 rows in set (0.00 sec)
Following is the query to check if a string contains a word in a column −
Note − Below displays for a single word as a column value. The same works for an entire line or string, wherein you need to find only a word −
mysql> select Value from DemoTable where 'Relational' LIKE concat('%',Value,'%');
This will produce the following output −
+------------+ | Value | +------------+ | Relational | +------------+ 1 row in set (0.00 sec)
Issue
my model order has a text field as: order.remark.
how to filter orders with the remark field containing certain word? e.g. a reference number, a telephone number.
in the order remark field the user can input anything, how to filter orders with remark containing the words «SZFPS/LCB-D2232», for instance. Please be noted that user might type in a lot of information without enter space, i.e. the words are not seperated by space or tab or any sort of delimeters. how to effectively filter the orders?
Solution
will your Order
model has a field named remark
, to filter objects containing a certain remark you can use __contains
for having the case sensitivity or use __icontains
to ignore the case sensitivity. so you can filter as follow
Order.objects.filter(remark__icontains="your searching phrases")
Answered By – Ali Aref
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0
-
Home
- If field_1 contains %word% return field_2 with MySQL and PHP
209 votes
2 answers
Get the solution ↓↓↓
About the technologies asked in this question
PHP
PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
MySQL
DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL.
It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/
Welcome to programmierfrage.com
programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.
Get answers to specific questions
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Help Others Solve Their Issues
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.