Pergunta

I use the same query in my book. Then, why is my output much different from that given in the book ? The book also says "the || operator does not lead to the concatenation of alphanumeric values, but it is regarded as an OR operator to combine predicates". What does the "an OR operator to combine predicates" mean ?

  • database: tennis
  • table: player
  • columns: playerno(pk), town, street, houseno ...etc.

  • Problem: Get the player number and the address of each player who lives in stratford

  • Query:

    select playerno, town || '' || street || '' || houseno
    from players 
    where town = 'stratford';
    
  • Book's result:

    2   Stratford Stoney Road 43
    6   Stratford Haseltine lane 80
    

......etc

  • My result(using the same query):

    2   1
    6   1
    7   1
    39  1
    57  1
    83  1
    100 1 
    
Foi útil?

Solução

In MySQL, you have to use CONCAT() to bring the values of the columns together in one string:

SELECT playerno, CONCAT(town, ' ', street, ' ', houseno)
FROM   players 
WHERE  town = 'stratford';

Your book is perhaps referring to the Oracle concatenation syntax which uses || to concat strings. MySQL, by default, treats || as an OR operator between two or more conditions, returning 1 if either of them evaluate to "true".

But as noted in satdev86's answer, MySQL does permit the use of || as a concatenation operator only if the mode PIPES_AS_CONCAT is manually set before you execute your query.


EDIT:

In your book, it clearly states you have to set the MySQL sql_mode for the examples to work. It's on the page prior to your SQL example:

http://books.google.com/books?id=c5G42OHT96cC&pg=PT160&lpg=PT160&dq=%22This+specification+is+needed+for+the+following+examples.+It+applies+only+to+the+current+session.%22&source=bl&ots=6b6zeFbM-2&sig=3a54S4vbgmKbPBqVbbR8OdxLLI8&hl=en&sa=X&ei=Nwz9T6fKAcfI2gWZhfDTBg&ved=0CCEQ6AEwAA

Outras dicas

Because, As per book, if they have used a sql mode PIPES_AS_CONCAT, then your pipes will act as concatenation operator.

SET sql_mode='PIPES_AS_CONCAT';
select playerno, town || '' || street || '' || houseno
from players 
where town = 'stratford';

will give you the output as you see in book :)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top