检查用户是否存在于其他表中时查询出错

时间:2013-10-21 15:01:58

标签: mysql join

我的查询显示了每个版本的修订员工的列表..

现在我正在尝试显示给定员工在答案表中是否已经有一行......

这是数据库的概述

enter image description here

这是我的工作查询,显示修订和员工列表

SELECT l.id, l.naam, r.id as revision_id, r.beschrijving, e.id as employee_id, e.voornaam, e.achternaam,
FROM lists l
INNER JOIN revisions r ON l.id = r.list_id
INNER JOIN employeelists el ON el.list_id= l.id
INNER JOIN employees e ON e.id = el.employee_id
INNER JOIN customers c ON c.id = e.customer_id
WHERE customer_id = :id AND r.actief = 1

enter image description here

现在我已经尝试了几件事来看看员工是否已经在答案表中有记录了......但是它一直没有成功..

尝试1:添加带有左外连接的Answers表

SELECT l.id, l.naam, r.id as revision_id, r.beschrijving, e.id as employee_id, e.voornaam, e.achternaam,
**CASE WHEN a.coach_id != 0 THEN 1 ELSE 0 END as FILLED IN**
FROM lists l"""
INNER JOIN revisions r ON l.id = r.list_id
**LEFT OUTER JOIN answers a ON a.revision_id = r.id**
INNER JOIN employeelists el ON el.list_id= l.id
INNER JOIN employees e ON e.id = el.employee_id
INNER JOIN customers c ON c.id = e.customer_id
WHERE customer_id = :id AND r.actief = 1

现在的问题是,每位员工都会多次出现...... enter image description here

这是工作数据库的SQLFiddle,我唯一不能做的就是检查给定的员工(werknemer)是否存在于答案(antwoorden)表中。

http://sqlfiddle.com/#!2/0c01c/4

我对如何解决这个问题有任何想法?我尝试了一个子查询,但这也没有用。谢谢!

立即查询

的问题

我认为我是对的,但还有一个错误。在 answer 表中,它显示 werknemer_id(employee_id)= 78 的结果。对于 revisie(修订版)1和2

虽然只有revisie 1的结果(截图如下)

enter image description here

enter image description here

谢谢!

2 个答案:

答案 0 :(得分:0)

如果不存在于antwoorden,则该存在列将具有0,如果存在则为1

    SELECT l.id, l.naam, r.revisie as revisie, r.id as revisie_id, r.beschrijving, w.id as werknemer, w.voornaam, w.achternaam
    , a.werknemer_id,
(CASE WHEN a.werknemer_id IS NULL THEN 0 ELSE 1 END ) AS `exist`
    FROM lijsten l
    INNER JOIN revisies r ON l.id = r.lijst_id
    INNER JOIN werknemerlijsten wl ON wl.lijst_id = l.id
    INNER JOIN werknemers w ON w.id = wl.werknemer_id
    INNER JOIN klanten k ON k.id = w.klant_id
    LEFT JOIN   antwoorden a ON w.id = a.werknemer_id
    WHERE klant_id = 39 AND r.actief = 1
    GROUP BY  r.beschrijving, w.id

Fiddle

答案 1 :(得分:0)

最终解决方案

这是最后的结果,只有当所需的教练(在这种情况下为1)在答案表中时,才会看到'ingevuld'为1。

SELECT l.id, l.naam, r.revisie AS revisie, r.id AS revisie_id, r.beschrijving, w.id AS werknemer, w.voornaam, w.achternaam, a.coach_id,
CASE WHEN a.coach_id = 1 THEN 1 ELSE 0 END AS ingevuld
FROM lijsten l
INNER JOIN revisies r ON l.id = r.lijst_id
INNER JOIN werknemerlijsten wl ON wl.lijst_id = l.id
INNER JOIN werknemers w ON w.id = wl.werknemer_id
INNER JOIN klanten k ON k.id = w.klant_id
LEFT JOIN antwoorden a ON w.id = a.werknemer_id AND r.id=a.revisie_id
WHERE klant_id = 39 AND r.actief = 1
group by r.id, w.id, a.coach_id