将另一个表中的列数据用于两个连接表的where子句

时间:2018-04-06 07:27:08

标签: mysql sql

我基本上有三个表,trans,master和period。我想显示来自trans和master的数据,但是使用from子句中的数据。

这是我当前的查询,但它从第三行返回错误1064:

SELECT b.projname AS companies,SUM(otreg_h) AS hours, SUM(otreg_m) AS minutes FROM trans AS a
JOIN MASTER AS b ON a.empno = b.empno
WHERE otreg_h != 0 AND otreg_m != 0 AND pdate BETWEEN STRDate IN(SELECT STRDate FROM period) AND ENDDate IN (SELECT ENDDate FROM period)
GROUP BY b.projname
ORDER BY SUM(otreg_h) DESC LIMIT 15

我在这里做错了什么?

编辑:这是表'期间'的当前结构

PayCat - varchar(1) NOT NULL
PayMonth - int(10) NULL
PeriodNo - int(10) NULL
(Foreign key)STRDate - date NOT NULL
(Foreign key)ENDDate - date NOT NULL
PAYDate - date NULL
Processed - tinyint(3) NOT NULL
Posted - tinyint(3) NOT NULL
Pyear - varchar(50) NULL
id - bigint(10) NOT NULL
date1 - date NULL
date2 - date NULL

3 个答案:

答案 0 :(得分:0)

我有点犹豫要不要在这里提供答案,因为我不确定是否有正确的答案,但鉴于评论pdate应该在STRDate和ENDDate之间,而不是其他任何事情,那么下面的比较会做< / p>

 pdate BETWEEN (SELECT MIN(STRDate) FROM period) AND (SELECT MAX(ENDDate) FROM period)

因此完整的查询将是

SELECT b.projname as companies, sum(otreg_h) as hours, sum(otreg_m) as minutes 
FROM trans a
JOIN master b on a.empno=b.empno
WHERE otreg_h != 0 AND otreg_m != 0
AND pdate BETWEEN (SELECT MIN(STRDate) FROM period) AND (SELECT MAX(ENDDate) FROM period)
GROUP BY b.projname
ORDER BY hours DESC LIMIT 15

答案 1 :(得分:-1)

你已经使用strdate 2次

SELECT
  b.projname AS companies,
  SUM(otreg_h) AS hours,
  SUM(otreg_m) AS minutes
FROM
  trans AS a
  JOIN MASTER AS b ON a.empno = b.empno
WHERE
  otreg_h != 0
  AND otreg_m != 0
  AND pdate BETWEEN (
    SELECT
      STRDate
    FROM
      period
  )
  AND ENDDate IN (
    SELECT
      ENDDate
    FROM
      period
  )
GROUP BY
  b.projname
ORDER BY
  SUM(otreg_h) DESC
LIMIT
  15

答案 2 :(得分:-1)

SELECT b.projname AS公司,SUM(otreg_h)AS小时,SUM(otreg_m)AS分钟FROM trans AS a JOIN MASTER AS b on a.empno = b.empno WHERE otreg_h!= 0 AND otreg_m!= 0 AND pdate BETWEEN(STRDATE IN(SELECT STRDate FROM period))AND(ENDDate IN(SELECT ENDDate FROM period)) GROUP BY b.projname ORDER BY SUM(otreg_h)DESC LIMIT 15