开发者

SQL Query - Left Join or Union?

开发者 https://www.devze.com 2023-04-10 05:49 出处:网络
How do I write a SQL 开发者_运维技巧query to find out what the group ID is and then display list of Options from that Group ID.

How do I write a SQL 开发者_运维技巧query to find out what the group ID is and then display list of Options from that Group ID.

I can do it by two queries, for example:

//Get the group ID 
SELECT option_group_id FROM options WHERE id =14122

//Now get a list of OptionID from that group ID
SELECT id, name FROM options WHERE option_group_id = 999

How do I put this into 1 query?


You could use a subquery to retrieve the group's id:

select  id
,       name
from    options
where   option_group_id = 
        (
        select  option_group_id
        from    options
        where   id = 14122
        )


Basically:

  • if you want more columns => join
  • if you want more rows => union

In this case:

SELECT toGetData.id
     , toGetData.name
  FROM options toGetId
  join options toGetData on toGetData.option_group_id = toGetId.option_group_id
 wHERE toGetId.id = 14122


Neither. You use an inner join against the same table:

select o2.id, o2.name
from options o1
inner join options o2 on o2.option_group_id = o1.option_group_id
where o1.id = 14122
0

精彩评论

暂无评论...
验证码 换一张
取 消