Mysql查询两个具有空值的表

时间:2018-02-08 07:04:17

标签: mysql

有两个表,一个是客户和其他奖金额

**Customer**          **PrizeAmount**
*CustomerId Amount*      *CustomerId PrizeAmt*   
1  500                   1          2000
                         1          2000

结果查询应该是这样的

CustomerId Amount PrizeAmt
1          500     2000
1          (NULL)  2000

那么如何为上述结果编写查询

2 个答案:

答案 0 :(得分:1)

使用左连接可以执行此操作

SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;

所以

select customer_id as custo_id,amount,prize_amt 
from customer 
left join prize_amount on customer.customer_id=prize_amount.customer_id

Left Join

答案 1 :(得分:0)

也许这个

DROP TABLE IF EXISTS T,T1;

CREATE TABLE T (CID INT , AMOUNT_INVESTED INT);
CREATE TABLE T1 (CID INT, AMOUNT_WON INT);
INSERT INTO T VALUES (1,500);
INSERT INTO T1 VALUES (1,2000),(1,2000);

SELECT CID,AMOUNT_INVESTED,AMOUNT_WON
FROM
(
SELECT T.CID,IF(T.CID <> @P, T.AMOUNT_INVESTED,NULL) AMOUNT_INVESTED, T1.AMOUNT_WON,
         @P:=T.CID
FROM T
JOIN T1 ON T.CID = T1.CID
CROSS JOIN (SELECT @P:=0) P
) S

+------+-----------------+------------+
| CID  | AMOUNT_INVESTED | AMOUNT_WON |
+------+-----------------+------------+
|    1 |             500 |       2000 |
|    1 |            NULL |       2000 |
+------+-----------------+------------+
2 rows in set (0.00 sec)