Jump to content


Photo

Dúvida Sql


  • Faça o login para participar
16 replies to this topic

#1 michelsinclair

michelsinclair

    Normal

  • Usuários
  • 78 posts
  • Sexo:Não informado

Posted 05/02/2007, 09:29

pessoal... tenho um campo chamado produtos e nele tenho por exemplo os seguintes valores:

1. exemplo) "moveis cadeira mesa escritório"
2. exemplo) "cadeira mesa escritório"

Digamos que o usuario esteja localizando por "móveis escritório"

eu gostaria que me retorna-se somente os que contiverem obrigatóriamente as duas palavras no campo, no caso seria o exemplo 1.

O google faz este tipow de busca... alguém aí sabe como eles conseguem?

Agradeço a todos desde já

#2 Petry

Petry

    Veterano

  • Usuários
  • 1132 posts
  • Sexo:Masculino
  • Localidade:Caxias do Sul - RS
  • Interesses:- desenvolvimento WEB<br />- websemântica<br />- microformatos

Posted 05/02/2007, 10:06

pode ser feito de várias formas, mas geralemnte eu faço o seguinte

recebo as variaveis e guardo elas em uma array, utilizando o explode e depois crio um consulta dinamica utilizando UNION de acordo com as palavras encontradas
SELECT * FROM tabela WHERE campo = 'mesa'
UNION
SELECT * FROM tabela WHERE campo = 'cadeira'
UNION
SELECT * FROM tabela WHERE campo = 'escritorio'

Posted Image

- Desenvolvedor Python/ZOPE/Plone + ArchGenXML/Poseidon - Python + Django na Universidade de Caxias do Sul
- Desenvolvedor Python + Django na World News

Blog

#3 Noturno

Noturno

    12 Horas

  • Usuários
  • 183 posts
  • Sexo:Não informado

Posted 05/02/2007, 10:31

Com o exemplo do Petry é possível, mas não viável, ele vai fazer várias consultas causando uma sobrecarga desnecessária.
Qual banco utilizado?
O SQL Server tem uma ferramenta chamada Full-Text Search, outros bancos devem ter(Oracle ex.) mas desconheço.

Segue ai o tópico referente ao full-text no Books Online do SQL:

Full-Text Indexes
Full-text support for Microsoft® SQL Server™ 2000 data involves two features: the ability to issue queries against character data, and the creation and maintenance of the underlying indexes facilitating these queries.

Full-text indexes differ from regular SQL indexes in a number of ways.

Regular SQL indexes Full-text indexes
Stored under the control of the database in which they are defined. Stored in the file system, but administered through the database.
Several regular indexes per table are allowed. Only one full-text index per table is allowed.
Updated automatically when the data upon which they are based is inserted, updated, or deleted. Addition of data to full-text indexes, called population, can be requested through either a schedule or a specific request, or can occur automatically with the addition of new data.
Not grouped. Grouped within the same database into one or more full-text catalogs.
Created and dropped using SQL Server Enterprise Manager, wizards, or Transact-SQL statements. Created, managed, and dropped using SQL Server Enterprise Manager, wizards, or stored procedures.


These differences make a number of administrative tasks necessary. Full-text administration is carried out at several levels:

Server
Certain server-wide properties, such as resource_usage, can be set to increase and reduce the amount of system resources used by the full-text service.



Note The full-text engine runs as a service named Microsoft Search on Microsoft Windows NT® Server and Microsoft Windows® 2000 Server. The Microsoft Search service is not available for Microsoft SQL Server Personal Edition. Although this means the Microsoft Search service is not installed on Microsoft Windows 95 or Windows 98, Windows NT Workstation, or Windows 2000 Professional clients, these clients can make use of the service when they are connected to an instance of SQL Server Standard or Enterprise edition.

Database
A database must be enabled to use the full-text service. Meta data for one or more full-text catalogs can be created and dropped in an enabled database.

Full-text catalog
A full-text catalog contains full-text indexes in a database. Each catalog can serve the indexing needs of one or more tables within a database. The catalog is populated with indexes using the administrative facilities described here. (Full-text catalogs must reside on a local hard drive associated with the instance of SQL Server. Removable drives, floppy disks, and network drives are not supported.) A maximum of 256 full-text catalogs can be created on each server.



Note Full-text indexing is fully supported in a Windows NT failover cluster environment. For more information, see Running Full-Text Queries with Failover Clustering.

Table
A table must first be enabled for full-text support. Then meta data, such as the name of the table and its full-text catalog, is created for the full-text index associated with the table. After the table is enabled, you can populate it with the data in columns enabled for full-text support. If the full-text definition for a table is changed (for example, by including a new column that will also be indexed for a full-text search), the associated full-text catalog must be repopulated to synchronize the full-text index with the new full-text definition.

Column
Columns that support full-text queries can be added or dropped from an inactive registered table.

At all these levels, facilities are available to retrieve meta data and status information.

Like regular SQL indexes, full-text indexes can be automatically updated as data is modified in the associated tables. Alternatively, full-text indexes can be repopulated manually at appropriate intervals. This repopulation can be time-consuming and resource-intensive; therefore, it is an asynchronous process that usually runs in the background during periods of low database activity.

Tables with the same update characteristics (such as small number of changes versus large number of changes, or tables that change frequently during a particular time of day) should be grouped together and assigned to the same full-text catalog. By setting up full-text catalog population schedules in this way, full-text indexes stay synchronous with the tables without adversely affecting the resource usage of the database server during periods of high database activity.

It is important to plan the placement of full-text indexes for tables in full-text catalogs. When you assign a table to a full-text catalog, consider the following guidelines:

Always select the smallest unique index available for your full-text unique key. (A 4-byte, integer-based index is optimal.) This reduces the resources required by Microsoft Search service in the file system significantly. If the primary key is large (over 100 bytes), consider choosing another unique index in the table (or creating another unique index) as the full-text unique key. Otherwise, if the full-text unique key size reaches the maximum size allowed (450 bytes), full-text population will not be able to proceed.


If you are indexing a table that has millions of rows, assign the table to its own full-text catalog.


Consider the amount of change occurring in the tables being full-text indexed, as well as the number of table rows. If the total number of rows being changed, together with the numbers of rows in the table present during the last full-text population, represents millions of rows, assign the table to its own full-text catalog.


O Full-Text faz exatamente o que a pesquisa do Google faz(Não tudo igual, claro).
Exemplo:
Pra pesquisar no banco no seu caso vc faria

móveis + escritório

E ele retornaria o que vc quer

Edições do SQL Server e Full Text Search
Antes de você iniciar o processo de instalação do SQL Server 2000, você precisa determinar qual versão e edição do SQL Server deseja utilizar e se instalará o Full Text Search. O SQL Server 2000 Standard Edition é o mais adequado para a maioria dos servidores de produção. O SQL Server 2000 Enterprise Edition oferece recursos mais avançados como, por exemplo, suporte a failover clustering. O SQL Server 2000 Enterprise Edition incorporou ainda a capacidade de gerenciar grandes tabelas através de múltiplos servidores.

Ambas as edições do SQL Server 2000 podem rodar no Win2K Server, Win2K Advanced Server, Win2K Datacenter Server, NT Server 4.0, Standard Edition com SP5 ou posterior, e ainda, no NT Server 4.0, Enterprise Edition com SP5 ou posterior. A Microsoft diz que views indexadas rodam apenas no SQL Server 2000 Enterprise Edition, porém, eu já experimentei executá-las no SQL Server 2000 Standard Edition sem problemas.

A Microsoft lançou o SQL Server 2000 Personal Edition para desenvolvedores e outros que tivessem a necessidade de possuir uma cópia local do SQL Server, talvez em um notebook que fosse utilizado também fora do escritório. Essas edição, mais simples, perde algumas das funcionalidades - por exemplo, ela não incorpora o Full Text Search. Se você está instalando o SQL Server no Win2K Professional, NT Workstation, Windows Me, ou Windows 9x, apenas a Personal Edition funcionará. Escolhendo a Standard Edition em qualquer uma dessas plataformas, gerará uma mensagem de erro.

O serviço Full Text Search utiliza muitos dos mesmos componentes do Microsoft Index Server. Esse serviço permite a desenvolvedores indexar dados no formato texto e fazer buscas que contenham as palavras ou as frases procuradas. O recurso oferecido pelo serviço Full Text Search exige uma razoável quantidade de espaço em disco para indexar os textos. A instalação do Full Text Search no SQL Server 2000 acontece mesmo na instalação típica, diferentemente da versão 7.0, ainda que você escolha a configuração mínima. Caso não instale esse recurso inicialmente, você pode, quando desejar, voltar a rodar o programa de instalação para fazê-lo.



http://www.microsoft.../col_sql_2.aspx
"Não há maior demonstração de insanidade do q fazer a mesma coisa, da mesma forma, dia após dia, e esperar resultados diferentes"
MCP .NET WebApplications C#
MCP SQL Server 2000
Desenvolvedor Delphi/PHP

#4 Petry

Petry

    Veterano

  • Usuários
  • 1132 posts
  • Sexo:Masculino
  • Localidade:Caxias do Sul - RS
  • Interesses:- desenvolvimento WEB<br />- websemântica<br />- microformatos

Posted 05/02/2007, 12:58

para mysql: http://dev.mysql.com...ext-search.html

Posted Image

- Desenvolvedor Python/ZOPE/Plone + ArchGenXML/Poseidon - Python + Django na Universidade de Caxias do Sul
- Desenvolvedor Python + Django na World News

Blog

#5 Noturno

Noturno

    12 Horas

  • Usuários
  • 183 posts
  • Sexo:Não informado

Posted 05/02/2007, 13:14

Prety vc não sabe como me deixou feliz em saber que o MySQL tem isso hahahahaha...
"Não há maior demonstração de insanidade do q fazer a mesma coisa, da mesma forma, dia após dia, e esperar resultados diferentes"
MCP .NET WebApplications C#
MCP SQL Server 2000
Desenvolvedor Delphi/PHP

#6 Petry

Petry

    Veterano

  • Usuários
  • 1132 posts
  • Sexo:Masculino
  • Localidade:Caxias do Sul - RS
  • Interesses:- desenvolvimento WEB<br />- websemântica<br />- microformatos

Posted 05/02/2007, 13:41

Prety vc não sabe como me deixou feliz em saber que o MySQL tem isso hahahahaha...


hehehe tu sabia q eu nem tinha me ligano nessa função, já havia utilizado para oracle uam vez, mas depois nunca mais, mas depois que voce postou eu pensei "perai... deve ter algo parecido para mysql..." :P

Posted Image

- Desenvolvedor Python/ZOPE/Plone + ArchGenXML/Poseidon - Python + Django na Universidade de Caxias do Sul
- Desenvolvedor Python + Django na World News

Blog

#7 Noturno

Noturno

    12 Horas

  • Usuários
  • 183 posts
  • Sexo:Não informado

Posted 05/02/2007, 14:17

Essa ferramenta é sensacional... uma xxxxxx mão na roda para os DBA's, se não fosse ela, nós ficariamos dias tentando otimizar o impossível ahhaha
"Não há maior demonstração de insanidade do q fazer a mesma coisa, da mesma forma, dia após dia, e esperar resultados diferentes"
MCP .NET WebApplications C#
MCP SQL Server 2000
Desenvolvedor Delphi/PHP

#8 michelsinclair

michelsinclair

    Normal

  • Usuários
  • 78 posts
  • Sexo:Não informado

Posted 06/02/2007, 09:44

Caraca... achei alucinante este recurso no MySQL.... muito útil mesmo... porém pro meu caso específico não resolveu... exemplo: procuro por 'banana maçã tomate'

me retornou: 'banana amarela bla bla bla'
'maçã argentina bla bla bla'

ele me retorna os campos que tenham a palavra banana OU maçã... eu preciso que me retorne exatamente a sentença completa digitada.

lembrando que:

tenho um campo chamado produtos e nele tenho por exemplo os seguintes valores:

1. exemplo) "moveis cadeira mesa escritório"
2. exemplo) "cadeira mesa escritório"

Digamos que o usuario esteja localizando por "móveis escritório"

eu gostaria que me retorna-se somente os que contiverem obrigatóriamente as duas palavras no campo, no caso seria o exemplo 1.

Será que naum tem solução para o meu caso?

#9 Noturno

Noturno

    12 Horas

  • Usuários
  • 183 posts
  • Sexo:Não informado

Posted 06/02/2007, 09:54

Dá uma lida no que eu falei, para trazer OBRIGATORIAMENTE os 2 utilize o operador "+"
"Não há maior demonstração de insanidade do q fazer a mesma coisa, da mesma forma, dia após dia, e esperar resultados diferentes"
MCP .NET WebApplications C#
MCP SQL Server 2000
Desenvolvedor Delphi/PHP

#10 michelsinclair

michelsinclair

    Normal

  • Usuários
  • 78 posts
  • Sexo:Não informado

Posted 06/02/2007, 10:54

Noturno,

tentei mas naum consegui... a minha sintaxe deve ter algum problema... mas naum esta retornando erro algum...


seguindo o exemplo do Mysql


SELECT * FROM articles WHERE MATCH (title,body) AGAINST ('database')+('following')

naum retornou nenhum registro e na base no campo body tem:

'In the following database comparison ...'

ajuda ae mano

#11 Noturno

Noturno

    12 Horas

  • Usuários
  • 183 posts
  • Sexo:Não informado

Posted 06/02/2007, 11:30

SELECT * FROM articles WHERE MATCH (title,body) AGAINST ('+database +following')

tente isso
"Não há maior demonstração de insanidade do q fazer a mesma coisa, da mesma forma, dia após dia, e esperar resultados diferentes"
MCP .NET WebApplications C#
MCP SQL Server 2000
Desenvolvedor Delphi/PHP

#12 michelsinclair

michelsinclair

    Normal

  • Usuários
  • 78 posts
  • Sexo:Não informado

Posted 06/02/2007, 13:26

cara... assim ele retornou como se naum tive-se o "+"
ou seja... retornou estes dois registros:

"In the following database comparison ... "
"DBMS stands for DataBase ... "

isto porque os dois tem a palavra 'database'... mas oq preciso é que retorne somente o primeiro resultado

que tem a palavra following e a palavra database...

ajuda-me please

#13 chipis

chipis

    24 Horas

  • Usuários
  • 439 posts
  • Sexo:Masculino
  • Localidade:Blumenau - SC

Posted 06/02/2007, 16:20

Tenta assim:

SELECT * FROM articles WHERE MATCH (title,body) AGAINST ('+following -database ')

#14 michelsinclair

michelsinclair

    Normal

  • Usuários
  • 78 posts
  • Sexo:Não informado

Posted 07/02/2007, 08:02

Chipis.... certamente assim não funcionará....

Alguém ae ... dá uma força

#15 Noturno

Noturno

    12 Horas

  • Usuários
  • 183 posts
  • Sexo:Não informado

Posted 07/02/2007, 08:33

michelsinclair,

me fala as colunas body e title do registro "DBMS stands for DataBase ... "

Do jeito que eu falei deveria funcionar, atente para essa parte no link que o Prety passou:

E aqui estão alguns exeplos:

*

apple banana

encontra linhas que contenha pela menos uma destas palavras.
*

+apple +juice

... ambas as palavras.
*

+apple macintosh

... palavra ``apple'', mas avaliada mais alto se também conter ``macintosh''.
*

+apple -macintosh

... palavra ``apple'' mas não ``macintosh''.
*

+apple +(>turnover <strudel)

... ``apple'' e ``turnover'', ou ``apple'' e ``strudel'' (em qualquer ordem), mas avalia ``apple pie'' melhor que ``apple strudel''.
*

apple*

... ``apple'', ``apples'', ``applesauce'', e ``applet''.
*

"some words"

... ``some words of wisdom'', mas não ``some noise words''.


"Não há maior demonstração de insanidade do q fazer a mesma coisa, da mesma forma, dia após dia, e esperar resultados diferentes"
MCP .NET WebApplications C#
MCP SQL Server 2000
Desenvolvedor Delphi/PHP




0 user(s) are reading this topic

0 membro(s), 0 visitante(s) e 0 membros anônimo(s)

IPB Skin By Virteq