从多个表

时间:2018-02-15 15:12:34

标签: mysql

费用表....状态1显示费用在所有班级中都很常见......     和状态2是不常见的费用................

+--------+------------------+-------------+--------+
| fee_id | fee_name         | duration_id | status |
+--------+------------------+-------------+--------+
|      1 | Admission Fee    |           4 |      1 |
|      2 | Re-admission Fee |           4 |      1 |
|      3 | Tuition Fee      |           1 |      1 |
|      4 | Computer Lab Fee |           1 |      2 |
|      5 | Science Lab Fee  |           1 |      2 |
|      6 | Exam Fee         |           2 |      1 |
|      7 | Electricity Fee  |           3 |      1 |
|      8 | Transport Fee    |           1 |      1 |
|      9 | Late Fee         |           1 |      1 |
+--------+------------------+-------------+--------+`

班级表....................

+----------+------------+
| class_id | class_name |
+----------+------------+
|        1 | Nursery    |
|        2 | L.K.G      |
|        3 | U.K.G      |
|        4 | 1          |
|        5 | 2          |
|        6 | 3          |
|        7 | 4          |
|        8 | 5          |
|        9 | 6          |
|       10 | 7          |
|       11 | 8          |
|       12 | 9          |
|       13 | 10         |
+----------+------------+

`在这里,我将不常见的费用映射到课堂上。

+----------+--------+
| class_id | fee_id |
+----------+--------+
|       10 |      4 |
|       10 |      5 |
|       11 |      4 |
|       11 |      5 |
|       12 |      4 |
|       12 |      5 |
|       13 |      4 |
|       13 |      4 |
+----------+--------+

我必须为类ID 10获取fee_names,包括所有常见费用和不常见费用属于该class_id。

2 个答案:

答案 0 :(得分:1)

试试这个(如果我理解你的要求):

select f.fee_name from fee f join uncommon_class c where f.fee_id = c.fee_id                
and c.class_id=10 union select fee_name from fee where status =1

答案 1 :(得分:0)

- 这对我来说似乎有点复杂,但应该是一种方法。 我们从费用中获取所有记录,然后离开加入课程,但仅限于class_ID 10。 然后我们只包含记录,其中class_ID为空,费用状态为1。

class_Fee表中只有class_ID的记录是10。

SELECT Fee_name
FROM Fee
LEFT JOIN Class_fee CF
 on Fee.Fee_ID = CF.Fee_ID
 and class_ID = 10
WHERE (CF.Class_ID is not null OR Fee.Status = 1)

- 工会方法似乎更直接

SELECT Fee_name 
FROM Fee 
WHERE status = 1
UNION
SELECT Fee_Name 
FROM Fee 
INNER JOIN Class_Fee CF 
  on CF.Fee_ID= Fee.Fee_ID
WHERE Class_ID = 10

如果你可以保证只有状态2记录得到映射,那么union可以是一个联合,通过避免distinct来获得一点性能。或者如果可以接受重复的名称,你可以使用union all