简体   繁体   中英

mysql - select email from xyz where email=“%gmail.com”

Is there a way I can select from the database the entries with certain data? I got a lot of email addresses in the database but I want to select only from one domain. Is it even possible?

Sure - just use the LIKE operator.

SELECT email FROM Persons
WHERE email LIKE '%gmail.com'

You are not advisable to do a wildcard search.
This is because mysql not able to use index to fasten the select query.
Especially you mention you have lots of email in the database.

Alternatively, you can use an additional field, as hostname to store just the hostname only.
And of course build an index to it.

If you need to search for email with gmail.com ,
then you can do straight string comparison

SELECT email FROM Persons
WHERE hostname='gmail.com';

As the straight string comparison is the good mate to mysql index, your query will be optimized.

As ajreal points out , MySQL can't use indexes to optimise a LIKE query in the general case. However in the specific case of a trailing wildcard where the only % is at the very end of the pattern (effectively a "starts with" query), the optimiser can do a good job of speeding up the query using an index.

Therefore, if you were to add an additional indexed column storing the email address in reverse, you could efficiently query for

SELECT email FROM xyz WHERE reverse_email LIKE 'moc.liamg@%`

to find all gmail addresses, or LIKE 'ku.% for all addresses under uk domains, etc. You can have the database keep this column up to date for you using triggers, so it doesn't affect your existing update code

CREATE TRIGGER emailinsert BEFORE INSERT ON xyz
FOR EACH ROW SET NEW.reverse_email = REVERSE(NEW.email);

CREATE TRIGGER emailupdate BEFORE UPDATE ON xyz
FOR EACH ROW SET NEW.reverse_email = REVERSE(NEW.email);

您需要使用LIKE MYSQL CLAUSE

SELECT * FROM email_table WHERE email LIKE "%gmail.com"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM