Question

I have two table, first, I need do some searching to get the fk of another table like this...

SELECT `related_table_id` 
FROM `table_a` 
WHERE `users_id` = '14' 
  AND `user_data_status` = 'n' 
  AND `another_table_name` = 'table_b'

then, I have many related_table_id as an output... and I need to search the content, which is like %keyword%. So, I need to query another SQL like this:

SELECT * 
FROM table_b 
WHERE (`table_b_id`='218' OR  `table_b_id`='219' OR  `table_b_id`='225') 
  AND `content` LIKE '%keyword%'

The question is, when my db grown, and the table_b, may have a lot of data that can query from table_a, so, the sql statement will become very very long. Can I combine these two statement in one? Thank you/

Was it helpful?

Solution

Do a nested query:

SELECT * FROM table_b WHERE `table_b_id` IN (SELECT `related_table_id` FROM `table_a` WHERE `users_id` = '14' AND `user_data_status` = 'n' AND `another_table_name` = 'table_b') AND `content` LIKE '%keyword%'

OTHER TIPS

You can use INNER JOIN to "match" the rows of two or more tables.

SELECT table_b.* 
FROM table_b 
INNER JOIN table_a
ON table_a.related_table_id = table_b.table_b_id
WHERE table_a.users_id = '14' 
  AND table_a.user_data_status = 'n' 
  AND table_a.another_table_name = 'table_b'
  AND table_b.content LIKE '%keyword%'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top