If you insist on storing data like you do, a possible solution (tested in T-SQL, question does not specify SQL flavor):
Setup
create table Recipes
(
RecipeId INT NOT NULL IDENTITY(1, 1) CONSTRAINT PK_Recipes PRIMARY KEY,
Name NVARCHAR(100),
Ingredients NVARCHAR(4000)
)
GO
insert into Recipes (Name, Ingredients) VALUES ('ciorba', 'apa,sare,piper,branza'), ('paste', 'branza,oua,lapte')
GO
create table Ingredients
(
IngredientId INT NOT NULL IDENTITY(1, 1) CONSTRAINT PK_Ingredients PRIMARY KEY,
Name NVARCHAR(100),
Ingredients NVARCHAR(4000)
)
GO
insert into Ingredients (Name, Ingredients) VALUES ('ionutG', 'branza'), ('vasile', 'oua,lapte')
GO
-- cannot remember what is the source for this - probably this
CREATE FUNCTION [dbo].[SplitStrings_XML]
(
@List NVARCHAR(MAX),
@Delimiter NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
(
SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
FROM
(
SELECT x = CONVERT(XML, '<i>'
+ REPLACE(@List, @Delimiter, '</i><i>')
+ '</i>').query('.')
) AS a CROSS APPLY x.nodes('i') AS y(i)
);
GO
select * from Recipes
select * from Ingredients
GO
-- split strings and retrieve records where intersection is not null
select distinct I.Name, I.Ingredients, R.Name
FROM Ingredients I
CROSS APPLY dbo.SplitStrings_XML(Ingredients, ',') IToken
JOIN Recipes R
CROSS APPLY dbo.SplitStrings_XML(Ingredients, ',') RToken
ON RToken.Item = IToken.Item
Note:. As already mentioned, you should really consider normalizing your data:
1) Performance - string operations are expensive and they should be avoided
2) Hard to write queries - a basic query for finding out common items uses a user defined function
3) Bad for application development - consider that the client also requires an English version for the application. Currently, all items are in Romanian. How to you handle this situation?
4) Bad for reports - consider that your structure requires extensive querying for reports regarding ingredients usage and other information. Those reports will have complex and messy queries which will be slow
[EDIT] For MySQL the following references may be used to replace unsupported features shown above:
Split strings using a method shown here.
Related questions and answers here and here.