1

I need to perform a search across 18 separate SQL tables for a string. The search will be looking in differently named fields and multiple fields on some tables.

While I can achieve this with something like the below (the first 2 tables), I feel the code is going to get very unwieldy once all 18 tables are joined.

Is there any way I can refine this code?

Also when the result is given can I find out with PHP which table the answer came from?

mysql_query("SELECT a.about,b.title,b.article,b.description

FROM about a 
JOIN articles b ON b.user=a.user

WHERE (upper(a.about)  LIKE'%".$val."%')  OR  (upper(b.title)  LIKE'%".$val."%') OR  (upper(b.article)  LIKE'%".$val."%') OR  (upper(b.descirption)  LIKE'%".$val."%')  ORDER BY $order $max");
10
  • Smells of SQL Injection... Commented Mar 9, 2014 at 16:09
  • Which kind of content is this? Why is it in 18 different tables? Feels like it's a database design problem, first of all. Commented Mar 9, 2014 at 16:10
  • I agree with @Qualcuno, sounds like a database design flaw. As to, "find[ing] out with PHP which table the answer came from", you could always label your selected columns with a prefix: "a.about as a_about". Commented Mar 9, 2014 at 16:12
  • The tables have to be separate, that's just the way it is. Commented Mar 9, 2014 at 16:19
  • 1
    @user1209203 Google "mysql full text". A starter could be: blog.marceloaltmann.com/… If you use "LIKE" MySQL can't use indexes and so the search can be PAINFULLY slow (as the db needs to go through all rows every time) Commented Mar 9, 2014 at 21:38

2 Answers 2

1

Use UNION

SELECT about from some WHERE about like '%some%'
UNION 
SELECT about from some_other WHERE about like '%some%'

and if you want to allow duplicate results use UNION ALL

Sign up to request clarification or add additional context in comments.

Comments

0

take a look at the UNION operation.

select x from table_1 where blabla
union
select y from table_2 where blabla

and so on.

x and y must be the same format.

1 Comment

@lovor I am selecting different fields from each table though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.