简体   繁体   中英

How can I simplify this SQL statement?

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/

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%'

进行嵌套查询:

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%'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM