从一个表中选择数据,检查并从第二个表中提取值

时间:2013-06-26 23:08:20

标签: php mysql sql

我有一个类似下面的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) )

我想扩展它以从问题表'section_id'中提取第二列值,并将其加入到结果中。

最好的方法是什么? 感谢

2 个答案:

答案 0 :(得分:1)

从查看代码开始,我假设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) )

答案 1 :(得分:1)

根据你在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);