Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching two tables

Tags:

sql

php

mysql

I currently have following two tables:

CREATE TABLE files_list
(
    'listid' INT, 
    'name' VARCHAR(25), 
    'synonym' VARCHAR(25), 
    'description' VARCHAR(25)
);

CREATE TABLE files_tags
(
    'tag_name' VARCHAR(25), 
    'listid' INT
);

If someone uses the keyword "dragon ball", at the moment, I use following query to search my_list for possible matches:

SELECT * 
FROM files_list
WHERE name LIKE '%dragon%' 
OR synonym LIKE '%dragon%' 
OR description LIKE '%dragon%' 
OR name LIKE '%ball%' 
OR synonym LIKE '%ball%' 
OR description LIKE '%ball%' 

I am not sure how to search both tables using one query. I want to show the user following data in the search result: name, synonym, description and all tags.

My Questions 1. Is there any way to make the current mysql query shorter? 2. How can I combine it with files_tags table, - to show rows from files_list which has a match in files_tags, but not in files_list? - to show rows from files_list which has a match in files_list, but may not infiles_tags`?

You can see the current displayed result at http://hsbsitez.com/

like image 958
user58670 Avatar asked Jan 24 '09 22:01

user58670


People also ask

How do I search for data in two tables in SQL?

In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.

Can we SELECT from two tables in SQL?

In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables.

How do you SELECT data from multiple tables in a single query in SQL?

Below statement could be used to get data from multiple tables, so, we need to use join to get data from multiple tables. Syntax : SELECT tablenmae1.


1 Answers

It would make more sense to join the tables.

SELECT name, synonym, description, tag_name FROM `files_list` WHERE ( name LIKE '%dragon%' OR synonym LIKE '%dragon%' OR description LIKE '%dragon%' OR name LIKE '%ball%' OR synonym LIKE '%ball%' OR description LIKE '%ball%' )
OUTER JOIN files_tags on files_tags.listid = files_list.listid

OUTER JOIN will make sure all tags are selected, this will create duplicate rows when multiple tags per id are available, with the only difference being the tag

like image 150
Sijmen Avatar answered Oct 06 '22 00:10

Sijmen