0

I've been trying to find a way to get a value from a column using mysql query.

The column (lets talk about colors) has several foreign keys (with no foreign constraint). So imagine a shirt can have blue and black, the column "color" will have "1,10" being 1-Blue and 10-Black, both foreign keys.

I want to create query to search if the color blue is being used so I can prevent deleting that color from his original table. Although it sounds easy, I can't use:

SELECT * FROM shirt WHERE color LIKE '%$id%'

The problem if it there's no blue color being used it will still find the black (10) and give a true value to the query.

2 Answers 2

1
SELECT * FROM shirt WHERE FIND_IN_SET($id, color) > 0
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, it did work. I was unware of that precious function
1

Well.. if I understand your question right. You are storing the values as a comma seperated string. You want to search whether any t-shirt holds that color.

$colorToSearchFor = '1'; //blue.. sepearte it by comma to check for several colors at the same time e.g '1,10'
$sql = "SELECT * FROM shirt WHERE color IN(colorToSearchFor)";

//count the results, if it's more than one then a t-shirt has the specifik color assigned.

It would be recommendable to have two different tables. One for the t-shirts and one for the colors.

2 Comments

They are in different tables and i wan't to avoid deleting colors being used. This works perfectly, thank you
Oh, and one table for what colors each t-shirt holds :) that would be a better structure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.