简体   繁体   中英

How to search in parts of entries within a mysql database?

I'm working with a database that contains some "special" columns: There are "cells" of a table containing a single Name of eg a painter like "Turner, William"; some other contain an ID like "ID123" connected with a table of persons. But some cells contain two or more entries, like: "ID123 ; Turner, William" - they are always separated by ";"

My question is: Normaly I can use something like "SELECT - FROM - LEFT JOIN" for simple selections with one entry. Is there any possibility for working with more than one entry? Something like

SELECT artwork.nameid, artwork.artist,
       person.fullname
FROM   artworks
LEFT JOIN person ON person.id = [Part of String artwork.artist]

One of the important principles of a relational database is that each column contains a single value, not a composite value like you describe. And the values in a given column have the same type, not variable types.

So you should solve your problem by having two columns, one for an ID and the other for a Name. Don't try to store them together in the same column with a semicolon separator.

CREATE TABLE artworks (
  ...
  PersonID VARCHAR(5),   -- example: ID123
  Name     VARCHAR(100), -- example: Turner, William
  ...
);

That said, you might be able to do what you describe using some MySQL string functions .

For example you can use LOCATE(';' artwork.artst) to detect if there's a semicolon present in a given string. You can use SUBSTRING_INDEX(artwork.artist, ';', 2) to extract the second "field" from a semicolon-separate field.

The expression needed to solve your problem is bound to become terribly complex if you need to handle a variety of cases, like what if a column has the ID first instead of second? What if there are three or more fields separated by semicolons?

Please take the recommendation that it will be far easier to restructure your table so you always have one value in each column.

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