[英]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... 我有两个表,首先,我需要进行一些搜索以获取另一个表的fk,如下所示...
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%. 然后,我有许多related_table_id作为输出...,我需要搜索内容,就像%keyword%。 So, I need to query another SQL like this:
所以,我需要查询另一个这样的SQL:
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. 问题是,当我的数据库和table_b增长时,可能有很多可以从table_a查询的数据,因此,sql语句将变得非常长。 Can I combine these two statement in one?
我可以将这两个语句合而为一吗? Thank you/
谢谢/
You can use INNER JOIN
to "match" the rows of two or more tables. 您可以使用
INNER JOIN
来“匹配”两个或更多表的行。
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%'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.