简体   繁体   中英

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,

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM