使用一个SELECT的结果作为第二个SELECT的输入,然后是COUNT

时间:2017-07-12 00:55:25

标签: mysql sql

假设您有一个架构,您将员工与表中的thing1相关联,然后thing1与另一个表中的thing2相关联。我想要一个单一的查询,它返回与员工关联的thing2s的数量(由于与一个与员工相关联的thing1相关联)。

表:

employee_thing1(包含employeeID和thing1ID)

thing1_thing2(包含thing1ID和thing2ID)

这是我的抨击:

 SELECT thing1ID as 'thing1Result' from employee_thing1 where employeeID=?,
 (SELECT 'total' as Name, COUNT(id) from thing1_thing2 as Count where thing1ID=thing1Result);

4 个答案:

答案 0 :(得分:1)

也许只是使用子查询来获取' thing1Result'?

SELECT 'total' as Name, COUNT(thing2ID) as Count from thing1_thing2 where thing1ID 
in (SELECT thing1ID  from employee_thing1 where employeeID=?)

答案 1 :(得分:0)

这只是一个快速的刺,但也许是这样的;

SET @thing1Result := (SELECT thing1ID FROM employee_thing1 WHERE employeeID=?);
SET @total := (SELECT COUNT(ID) FROM thing_thing2 WHERE thing1ID=@thing1result);

可能尝试一下吗?

答案 2 :(得分:0)

COUNT(DISTINCT)表上需要LEFT OUTER JOIN这样的内容,它会计算不包含NULL值的不同值:

SELECT
    employee.employeeID,
    COUNT(DISTINCT employee_thing1.thing1ID) AS 'thing1Count',
    COUNT(DISTINCT thing1_thing2.thing2ID) AS 'thing2Count'
FROM employee
LEFT OUTER JOIN employee_thing1
    ON employee_thing1.employeeID = employee.employeeID
LEFT OUTER JOIN thing1_thing2
    ON thing1_thing2.thing1ID = employee_thing1.thing1ID
WHERE employee.employeeID = ?

答案 3 :(得分:0)

在3个表上运行内部联接可以为您提供所需的内容。

SELECT COUNT(1) AS 'count' FROM `thing1_thing2` 
INNER JOIN `employee_thing1` ON `thing1_thing2`.`thing1ID` = `employee_thing1`.`thing1ID`
INNER JOIN `employees` ON `employee_thing1`.`emplyeeID` = `employees`.`emplyeeID`;