Comparing two values ββin one column
I need to compare a value in one column in one table. Here's an example table:
ID Cat Color ======================= 1 red maroon 2 red orange 3 red pink 4 blue violet 5 blue purple 6 blue indigo 7 green puke green 8 green hunter green
I am given 2 colors from the Color column. I need to know if they belong to the same Cat column. For example, I will be given maroon and orange. I need to return a red value. Violet and violet should return blue. Puke green and purple must return zero.
So far, I have the following SQL, but it is not exactly what I am looking for, especially with Limit 1. I am looking for a single query to return a Cat field without using Limit 1.
SELECT Cat From foo WHERE Color = 'maroon' and Color = 'orange' LIMIT 1
source to share
In addition to Beginner 's answer , it is possible to solve this problem without GROUP_CONCAT
:
SELECT cat
FROM foo
WHERE color IN ('maroon', 'orange')
GROUP BY cat
HAVING COUNT(*) = 2
;
This works by selecting all cats with the specified colors. When we group them, the cats that appear multiple times (suggestion HAVING
) are the entries you want to keep.
Note. The number using the sentence HAVING
should match the number of colors you are looking for.
source to share
You can try this:
SELECT x.cat
FROM (
SELECT cat, GROUP_CONCAT(color) AS colors
FROM tablename
GROUP BY cat) AS x
WHERE FIND_IN_SET('maroon', x.colors) > 0
AND FIND_IN_SET('orange', x.colors) > 0
Edit 1: Another alternative
SELECT IF(
FIND_IN_SET('maroon', GROUP_CONCAT(color)) > 0
AND FIND_IN_SET('orange', GROUP_CONCAT(color)) > 0 , cat, NULL
) AS cat
FROM tablename
GROUP BY cat
source to share