1

I am working on the query

(Select d_name from Direction where d_name  SIMILAR TO '(WEST|NORTH)%' )
this gives me the result as 
WEST 1
WEST 2
NORTH 2
WEST 
NORTH

But I want the result as

WEST
NORTH 

with the same statement Similar To. Someone please modify the same query to get the 2nd result. Thanks

dhS
  • 3,739
  • 5
  • 26
  • 55

3 Answers3

3
(select 'WEST' from Direction where d_name  SIMILAR TO 'WEST%')
UNION
(select 'NORTH' from Direction where d_name  SIMILAR TO 'NORTH%');
ddb
  • 2,423
  • 7
  • 28
  • 38
1

I got the solution

Select d_name 
from Direction 
where d_name  SIMILAR TO '(WEST|NORTH)' 

Just remove % from the query.

dhS
  • 3,739
  • 5
  • 26
  • 55
  • 1
    but, for example, if 'WEST' value is not existing in any row of the table, but you only have 'WEST 1' kind of values, you will not have 'WEST' as results with your solution – ddb Jul 06 '16 at 07:45
  • @ddb: my understanding is that dhS _does_ want an "exact" match. But if a "wildcard" match is required, the wildcard would need to be added to each value: `SIMILAR TO '(WEST%|NORTH%)'` –  Jul 06 '16 at 07:51
  • 1
    @a_horse_with_no_name, it's not anymore clear for me what he/she wants :) I thought I had a clear idea, but I don't now :) that's fine if he/she is happy of his/her own solution – ddb Jul 06 '16 at 07:55
1

If you are using MySQL, as it does not feature a split string function, you can create a user defined function for this, such as the one described in the following article:

With that function, you would be able to build your query as follows:

SELECT DISTINCT SPLIT_STR(d_name, ' ', 1)
FROM Direction
WHERE d_name SIMILAR TO '(WEST|NORTH)%';

If you prefer not to use a user defined function and you do not mind the query to be a bit more verbose, you can also do the following:

SELECT DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(d_name, ' ', 1), ' ', -1)
FROM Direction
WHERE d_name SIMILAR TO '(WEST|NORTH)%';

Disclaimer: I based this new answer on this solution

Community
  • 1
  • 1
ddb
  • 2,423
  • 7
  • 28
  • 38