在mysql中加入三个表

时间:2016-01-29 16:39:19

标签: mysql sql database

我有三张如下表。

Courses:
Id Name
1  A
2  B
3  C
4  D

Prices:
Id CId Price
1   1   200
2   2   150
3   3   500
4   4   300

Payment:
Id  CId
1    1
2    4

如果存在课程记录的付款记录,则Price应为-1。我想得到如下结果:

Id Name Price
1   A    -1
2   B    150
3   C    500
4   D     -1

我该如何查询mysql?

4 个答案:

答案 0 :(得分:1)

SQL Fiddle Demo 感谢@Barmar

SELECT C.ID, C.NAME, CASE WHEN pay.CId IS NULL THEN P.PRICE
                          ELSE -1
                     END as Price
FROM Courses C
JOIN Prices P 
  ON C.Id = P.CId
LEFT JOIN Payment pay
  ON C.id = pay.CId
ORDER BY P.id  

<强>输出

| Id | Name | Price |
|----|------|-------|
|  1 |    A |    -1 |
|  2 |    B |   150 |
|  3 |    C |   500 |
|  4 |    D |    -1 |

答案 1 :(得分:1)

工作代码:

select c.id, c.Name, IF(pm.CId is null, p.Price, -1) as Price
from Prices p left join Payment pm
on p.CId = pm.CId 
inner join Courses c 
on p.CId = c.id
order by c.id

SqlFiddle:http://sqlfiddle.com/#!9/f1b715/3

答案 2 :(得分:1)

试试这个

SELECT c.Id, c.name, 
CASE WHEN pa.id IS NOT NULL THEN -1 ELSE pr.price
END as Price
FROM Courses c
LEFT JOIN Prices pr 
ON c.Id = pr.CId
LEFT JOIN Payment pa
ON c.id = pa.CId;

OR

SELECT c.Id, c.name, 
CASE WHEN pa.id IS NULL THEN pr.price ELSE -1 
END as Price
FROM Courses c
LEFT JOIN Prices pr 
ON c.Id = pr.CId
LEFT JOIN Payment pa
ON c.id = pa.CId;

答案 3 :(得分:1)

SELECT p.id,c.NAME,CASE WHEN p.cid = e.cid THEN -1 ELSE p.price END AS price 来自价格p LEFT JOIN课程c ON c.id = p.ID LEFT JOIN付款e ON p.cid = e.cid