0

我有一个如下所示的 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”,并将其连接到结果中。

解决此问题的最佳方法是什么?谢谢

4

2 回答 2

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) )

于 2013-06-26T23:18:10.333 回答
1

根据您在 section_id 中的使用,我相信这个左连接应该可以工作:

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);
于 2013-06-26T23:19:50.603 回答