4

I have a complex query that does multiple matches across multiple columns and then orders by relevance.

Everything works fine UNTIL I add WHERE 'rank' > 0

This then returns an empty results set.

If I remove the 'WHERE' statement then I can see all results with the highest matches at the top.

Could someone help me work out 'WHERE' :-D I am going wrong!!

SELECT *, CASE WHEN companyName = 'gfdgfs' THEN 2 ELSE 0 END 
+ CASE WHEN companyName LIKE '%gfdgfs%' THEN 1 ELSE 0 END 
+ CASE WHEN companyName = 'potato' THEN 2 ELSE 0 END 
+ CASE WHEN companyName LIKE '%potato%' THEN 1 ELSE 0 END 
+ CASE WHEN address1 = 'gfdgfs' THEN 2 ELSE 0 END 
+ CASE WHEN address1 LIKE '%gfdgfs%' THEN 1 ELSE 0 END 
+ CASE WHEN address1 = 'potato' THEN 2 ELSE 0 END 
+ CASE WHEN address1 LIKE '%potato%' THEN 1 ELSE 0 END 
AS rank 
FROM clients 
WHERE rank > 0
ORDER BY rank

EDIT

I removed the single quotes around the rank word and now get 'unknown column rank in where clause'

Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
GrahamTheDev
  • 22,724
  • 2
  • 32
  • 64

2 Answers2

1

Remove single quotes from rank and try. Anyway, I don't think MySQL would support WHERE clause with aliases - check this.

Use HAVING rather than WHERE:

SELECT *, CASE WHEN companyName = 'gfdgfs' THEN 2 ELSE 0 END + CASE WHEN companyName LIKE '%gfdgfs%' THEN 1 ELSE 0 END + CASE WHEN companyName = 'potato' THEN 2 ELSE 0 END + CASE WHEN companyName LIKE '%potato%' THEN 1 ELSE 0 END + CASE WHEN address1 = 'gfdgfs' THEN 2 ELSE 0 END + CASE WHEN address1 LIKE '%gfdgfs%' THEN 1 ELSE 0 END + CASE WHEN address1 = 'potato' THEN 2 ELSE 0 END + CASE WHEN address1 LIKE '%potato%' THEN 1 ELSE 0 END AS rank FROM clients HAVING rank > 0 ORDER BY rank

Community
  • 1
  • 1
MusicLovingIndianGirl
  • 5,909
  • 9
  • 34
  • 65
0

Try this:

SELECT * 
FROM (SELECT *, CASE WHEN companyName = 'gfdgfs' THEN 2 ELSE 0 END 
              + CASE WHEN companyName LIKE '%gfdgfs%' THEN 1 ELSE 0 END 
              + CASE WHEN companyName = 'potato' THEN 2 ELSE 0 END 
              + CASE WHEN companyName LIKE '%potato%' THEN 1 ELSE 0 END 
              + CASE WHEN address1 = 'gfdgfs' THEN 2 ELSE 0 END 
              + CASE WHEN address1 LIKE '%gfdgfs%' THEN 1 ELSE 0 END 
              + CASE WHEN address1 = 'potato' THEN 2 ELSE 0 END 
              + CASE WHEN address1 LIKE '%potato%' THEN 1 ELSE 0 END 
              AS rank 
        FROM clients 
      ) AS A 
WHERE rank > 0
ORDER BY rank;
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
  • no doesnt work - musiclovingindiangirl got it right it was that `WHERE` doesnt work with an alias. Need to use `HAVING` instead. Thanks though. – GrahamTheDev Dec 24 '15 at 10:22