将同一个表的子查询替换为join

时间:2019-12-19 11:58:49

标签: sql sql-server join subquery

在这种情况下,无需子查询即可实现预期结果吗?也许使用联接?

我们有一个名字叫'jose',预期结果是所有行的颜色都与jose相同。查询应同时在MS-SQL和ORACLE中运行。

query
======
select name,color from tableA where color=(select color from tableA where name='jose')

Expected result 
===============
name    color
jose    red
Rap     red

schema
=======

Table and DATA
create table tableA (
name varchar(10),
color varchar(10)
);

insert into tableA values ('jose','red');
insert into tableA values ('Mickey','blue');
insert into tableA values ('Leo','yellow');
insert into tableA values ('Rap','red');
insert into tableA values ('Don','blue');

http://sqlfiddle.com/#!18/5f7e3/2

3 个答案:

答案 0 :(得分:2)

您可以通过JOIN字段的自联接来获得color的结果,其中第二个表中的名称为jose

SELECT a1.name, a1.color
FROM tableA a1
JOIN tableA a2 ON a2.color = a1.color AND a2.name = 'jose'

输出

name    color
jose    red
Rap     red

SQL Server demo on SQLFIddle

Oracle demo on SQLFiddle

答案 1 :(得分:0)

如果名称只有一种颜色,那么您似乎想要:

#pivot columns
values = pd.pivot_table(raw, values='COUNT_TICKS', index=['Z_LOC'], columns = ['X_LOC'], aggfunc=np.sum)

plt.figure(figsize=(20, 20))
sns.set(rc={'axes.facecolor':'cornflowerblue', 'figure.facecolor':'cornflowerblue'})
#ax = sns.heatmap(values, vmin=100, vmax=5000, cmap="Oranges", robust = True, xticklabels = x_labels, yticklabels = y_labels, alpha = 1)
ax = sns.heatmap(values, 
                 #vmin=1, 
                 vmax=1000, 
                 cmap="Greens",  #BrBG is also good
                 robust = True, 
                 alpha = 1)
plt.show()

如果您不想返回该行,则可能要添加另一个条件select a.* from tableA a where a.color = (select a2.color from tableA a2 where a2.name = 'jose');

答案 2 :(得分:0)

我认为最好的方法是“ CTE”:

     with 
     cte1 as (
          select 1 as RowToJoin,
                 name,
                 color 
          from tableA
     ),
     cte2 as (
          select 1 as RowToJoin,
                 color
                 name
          from tableA 
          where name='jose'
     )
     select c1.name, c1.color
     from cte1 c1
     join cte2 c2 on c2.RowToJoin = c1.RowToJoin
     where c1.name <> c2.name

看起来有些困难,但是很简单。尝试阅读一下。!