我试图从第二个表中选择ID,这个ID在我的第一个表中。我试过这个:
select
FIRST_NAME,
LAST_NAME,
c.name status
from STUDENTS
left join PAYER_STATUS c on Status = c.ID
where status like N'%'||'active'||'%';!
但它什么都没显示。这里只是清空一切。但是,如果我将活动更改为 0 ,则会显示状态列字活动。对于 1 无效等
我该如何解决?
答案 0 :(得分:2)
在where子句中使用您的列名。因为表格中有status
列。所以它将使用该列而不是c.name
select
s.FIRST_NAME,
s.LAST_NAME,
c.name as status
from STUDENTS s
left join PAYER_STATUS c on s.Status = c.ID
where c.name like N'%'||'active'||'%';!
答案 1 :(得分:1)
您不能在WHERE
/ ON
中使用列别名,此外,当LEFT JOIN
将外表的WHERE
子句条件移动到ON
子句时,否则它将是常规INNER JOIN
。
select FIRST_NAME,
LAST_NAME,
c.name status
from STUDENTS s
left join PAYER_STATUS c
on s.somecolumn = c.ID
and c.name like N'%'||'active'||'%';!
答案 2 :(得分:1)
我向您展示完整的测试用例,可能从下次您可以提供给我们,这样我们就可以轻松重现您的问题即可。因此我们不需要对这些表和所需数据进行反向工程和构建:
<强>设置强>
SQL> CREATE TABLE status(ID NUMBER, NAME VARCHAR2(20));
Table created.
SQL> CREATE TABLE students(NAME VARCHAR2(10), status VARCHAR2(20));
Table created.
SQL>
SQL> INSERT INTO status VALUES(0, 'ACTIVE');
1 row created.
SQL> INSERT INTO status VALUES(1, 'INACTIVE');
1 row created.
SQL> INSERT INTO status VALUES(2, 'SUSPEND');
1 row created.
SQL>
SQL> INSERT INTO students VALUES('a', 0);
1 row created.
SQL> INSERT INTO students VALUES('b', 0);
1 row created.
SQL> INSERT INTO students VALUES('c', 0);
1 row created.
SQL> INSERT INTO students VALUES('d', 1);
1 row created.
SQL>
<强>表格强>
SQL> SELECT * FROM status;
ID NAME
---------- --------------------
0 ACTIVE
1 INACTIVE
2 SUSPEND
SQL>
SQL> SELECT * FROM students;
NAME STATUS
---------- --------------------
a 0
b 0
c 0
d 1
SQL>
必填查询:
SQL> SELECT a.NAME,
2 a.status,
3 b.NAME
4 FROM students a
5 JOIN status b
6 ON (a.status = b.ID)
7 WHERE a.status = 0;
NAME STATUS NAME
---------- -------------------- ------
a 0 ACTIVE
b 0 ACTIVE
c 0 ACTIVE
SQL>