[英]select data from one table, check against and pull values from second table
I have a sql query like below, which is selecting values based on if they exist in the questions table and their section_id value falls within a certain range, 我有一个像下面这样的SQL查询,它根据问题表中是否存在它们的section_id值在一定范围内来选择值,
SELECT action_id, action_type, action_details, action_int, action_time
FROM actions
WHERE user_id = '".$id."'
AND action_type = 'other'
AND ( action_details = 'random question'
OR action_details = 'review')
AND action_int IN (
SELECT id
FROM questions
WHERE section_id IN (2,3,4,5,6,7,8) )
And I want to expand it to also pull a second column value from the questions table, 'section_id', and join it onto the results. 我想扩展它以从问题表'section_id'中提取第二列值,并将其加入到结果中。
What is the best way to go about this? 最好的方法是什么? Thanks
谢谢
从查看代码开始,我假设actions.action_int字段与questions.id字段相关,我相信这就是您所要求的:
SELECT actions.action_id, actions.action_type, actions.action_details, actions.action_int, actions.action_time, questions.section_id
FROM actions
JOIN questions
ON actions.action_int = questions.id
WHERE user_id = '".$id."'
AND action_type = 'other'
AND ( action_details = 'random question'
OR action_details = 'review')
AND action_int IN (
SELECT id
FROM questions
WHERE section_id IN (2,3,4,5,6,7,8) )
Based on your use of in in the section_id I believe this left join should work: 基于你在section_id中使用in我相信这个左连接应该有效:
SELECT a.action_id, a.action_type, a.action_details, a.action_int, a.action_time, q.section_id
FROM actions a left join questions q on a.action_int = q.id
WHERE a.user_id = '".$id."'
AND a.action_type = 'other'
AND a.action_details in('random question', 'review')
AND q.section_id IN (2,3,4,5,6,7,8);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.