[英]Nested where clause in MySQL
I have two tables: Event
and Story
-- the former has info about an event and the latter has the story text of those events. 我有两个表: Event
和Story
- 前者有关于事件的信息,后者有这些事件的故事文本。
I can get all the story_id
of the events that involve Brazil from Event
like so: 我可以从事件中获取涉及巴西Event
所有story_id
:
SELECT @story_id := `story_id` FROM events
WHERE actor_id='Brazil';
Then I want to query Story
using the story_id
I got. 然后我想使用我得到的story_id
来查询Story
。 How would I do that? 我该怎么办? Can I nest them somehow? 我能以某种方式筑巢吗?
UPDATE: I ended up storing story_id
in a temporary table instead of a variable. 更新:我最终将story_id
存储在临时表而不是变量中。 (New to MySQL, I have no idea how variable works here...) (MySQL的新手,我不知道变量在这里是如何工作的......)
CREATE TEMPORARY TABLE IF NOT EXISTS temp_table AS (SELECT story_id FROM events
WHERE actor_id='Brazil');
Then 然后
SELECT * FROM stories, temp_table
WHERE stories.StoryID = temp_table.story_id;
I'd appreciate any comment on this solution! 我很感激对此解决方案的任何评论!
You could do this, with a JOIN
: 你可以用JOIN
做到这一点:
SELECT @story_id := e.`story_id`, s.* FROM events e
INNER JOIN stories s ON s.StoryId = @story_id
WHERE e.actor_id='Brazil';
So the reason for the s
's and the e
's are to identify what tables you're selecting from. 所以对于原因s
的和e
的是确定你是从什么选择表。 You could just do FROM events
and INNER JOIN stories
, however, that's just the syntax I use to avoid typing out long table names. 你可以做FROM events
和INNER JOIN stories
,但这只是我用来避免输入长表名的语法。 You could just do this: 你可以这样做:
SELECT @story_id := events.`story_id`, stories.* FROM events
INNER JOIN stories ON stories.StoryId = @story_id
WHERE events.actor_id='Brazil';
However, as you probably notice, it's longer and not as simple. 但是,正如您可能已经注意到的那样,它更长,而不是那么简单。 Though it is easier to understand. 虽然它更容易理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.