简体   繁体   中英

Simple SQL Statement in Oracle

I have a two tables (Brands and Customers) in my database.

Brands

我的桌子

Customers

What I want is firstly looking up BRANDID for each customer. Then comapre if BRANDID matches agains BRANDID from BRANDS table. If matched, appropriate BRANDNAME goes in Customers BRANDNAME. If NOT matched, a string (Invalid) goes in Customers BRANDNAME.

Do I need to use INNER JOIN and CASE statement for this?

Oracle has its own outer join syntax, which is much nicer than standard SQL, but here's the ANSI SQL enquiry:

select customers.id,customers.brandid,
 if(brands.brandname is null,'Invalid',brands.brandname) as 'Brandname'
 from customers
 left join brands on (customers.brandid = brands.brandid) ;

You simply need an OUTER JOIN plus COALESCE:

select
   c.id,
   c.brandid,
   coalesce(b.brandname, 'Invalid')
from customers c
left join brands b on c.brandid = b.brandid;

This is pure Standard SQL and should run in any DBMS.

SQL Fiddle

UPDATE Customers c
SET BRANDNAME = COALESCE( ( SELECT b.BRANDNAME
                            FROM   Brands b
                            WHERE  c.BRANDID = b.BRANDID ),
                          'Invalid' );

Query 1 :

SELECT * FROM Customers

Results :

| ID | BRANDID | BRANDNAME |
|----|---------|-----------|
|  1 |       1 |     APPLE |
|  1 |       2 |       HTC |
|  1 |       3 |   SAMSUNG |
|  1 |      10 |   Invalid |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM