Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select records based on what a field begins with?

I have a database with a table that has identifiers c1, c2, c3..etc..

Instead of writing a query that has a bunch of ORs in it, how can I modify the below query with something that will catch all the records that begin with a certain letter?

SELECT 
    Person.spineinjuryAdmit, 
    tblComorbidity.comorbidityexplanation,
    Count(tblComorbidity.comorbidityexplanation) AS CountOfcomorbidityexplanation

FROM tblKentuckyCounties 
INNER JOIN (tblComorbidity 
            INNER JOIN (Person 
                        INNER JOIN tblComorbidityPerson 
                            ON Person.PersonID = tblComorbidityPerson.personID) 
                ON tblComorbidity.ID = tblComorbidityPerson.comorbidityFK) 
    ON tblKentuckyCounties.ID = Person.County
GROUP BY    Person.spineinjuryAdmit, 
            tblComorbidity.comorbidityexplanation
HAVING (((Person.spineinjuryAdmit)="c1" Or 
         (Person.spineinjuryAdmit)="c2" Or 
         (Person.spineinjuryAdmit)="c3"));
like image 424
dzilla Avatar asked May 31 '11 19:05

dzilla


2 Answers

Have you tried using LIKE? As an example:

SELECT * FROM patients WHERE lastName LIKE 'm%';

This would return records where patients.lastName starts with 'm'. The '%' character may be '*' for access, I can't remember. In some databases, you can also use '_' which will match a single character (or however many underscores you add).

like image 188
Rob Avatar answered Sep 28 '22 07:09

Rob


You can use regexp to query all rows that starts with several characters.

SELECT * FROM table WHERE column REGEXP '^[ c1, c2, c3]';

This query will return all rows where column starts with 'c1' or 'c2' or 'c3'.

like image 45
thodoris Avatar answered Sep 28 '22 07:09

thodoris