MYSQL在主查询中选择子查询结果的值

时间:2018-09-01 13:30:08

标签: mysql sql

我的sql查询是

 SELECT c_id
      , name
      , stu_id 
      , option_id
      , expiration_status 
      , expiration_date_type 
      , expiration_date_val 
   FROM options 
  WHERE option_id 
     IN 
      ( SELECT  option_id 
          FROM registration WHERE status NOT in ('C','T')
           AND structure = 'C' 
      ) 
  ORDER 
     BY structure
      , option_id ASC

这里我要选择在子查询中选择的option_id列表作为主查询中的新列

2 个答案:

答案 0 :(得分:0)

in上使用连接,然后根据需要在子查询中放置列名

SELECT `c_id`,`name`,`stu_id` ,`option_id`,`expiration_status` , `expiration_date_type` , `expiration_date_val`, t1.option_id as new_col
FROM `options` o  
 left join (
    SELECT  `option_id` 
    FROM `registration` 
    WHERE `status` NOT in ('C','T')
    AND `structure` = 'C' 
     ) t1 on o.option_id=t1.option_id
ORDER BY o.`structure`, o.`option_id` ASC

答案 1 :(得分:0)

您可以使用INNER JOIN来完成

SELECT o.c_id,o.name,o.stu_id ,o.option_id,o.expiration_status , 
 o.expiration_date_type , o.expiration_date_val
FROM `options` o
JOIN `registration` r ON r.option_id=o.option_id AND  r.status NOT in ('C','T')
    AND r.structure = 'C' 
    ORDER BY o.structure, o.option_id ASC