选择语句两次检索同一列

时间:2017-02-14 08:55:58

标签: mysql sql select

我有两张桌子:

表1名为 category_desription ,它包含2个字段: category_name category_id

表2命名类别包括 category_id parent_Category_id 字段,这些字段是第一个 category_id 中的外键表

我想选择4个字段,其结果将包含 category_id ,其名称 category_name parent_category_id 及其名称也恰好 category_name 以及

到目前为止,我无法弄清楚如何做到这一点,所以我希望有人能帮助我。

3 个答案:

答案 0 :(得分:1)

我希望这能解决你的问题

SELECT  category_id, 
(Select category_name from table1 where category_id= table2.category_id) as category_name , 
parent_category_id, 
(Select category_name from table1 where category_id= table2.parent_category_id) 
as parent_category_name from table2

答案 1 :(得分:0)

这是SQL中的简单名称冲突问题,可以使用alias

轻松解决

e.g。

Select t1.category_id, t1.category_name, t2.category_id, t2.category_name
from table1 t1 join table2 t2 on <some condition..>

您还可以为结果列提供不同的名称

 Select t1.category_id, t1.category_name as 'Parent Category Name',
 t2.category_id, t2.category_name as 'Category Name'
 from table1 t1 join table2 t2 on <some condition..>

我希望它能解决你的问题。

答案 2 :(得分:0)

 with category_desc as
 (select 1 as category_id, 'Category 1' as category_name
    from dual
  union all
  select 2 as category_id, 'Category 2' as category_name from dual),
category as
 (select 1 as category_id, 2 as parent_category_id from dual)
select c.category_id,
       c_d.category_name,
       c.parent_category_id,
       pc_d.category_name parent_category_name
  from category c
  join category_desc c_d
    on c_d.category_id = c.category_id
  join category_desc pc_d
    on pc_d.category_id = c.parent_category_id

使用具有不同别名的category_desc来查找parent_category详细信息