1

我无法从外部查询所需的子查询中的表 b 中获取单个值。在表 b 中有一组与表 a 和表 c 相关的日期。在这里我需要最新日期的目的代码才能成功执行查询。如果我删除子查询并写 where c. purpose_code = b. purpose_code 它运行正常,但结果较旧。请帮帮我。

SELECT
  a.filing_no AS "File No",
  a.case_no AS "Registration No",
  a.pet_name AS Petitioner,
  a.res_name AS Accused,
  a.dt_of_filing AS "Date of Inst",
  max(b.Next_date) AS "Next Date",
  c.purpose_name AS "Case Stage"
FROM
  filing_t a, Daily_proc b, Purpose_t c
WHERE
  a.filing_no = b.filing_no
  AND c.purpose_code = (
    SELECT purpose_code FROM Daily_proc
    WHERE filing_no = a.filing_no AND next_date = max(next_date)
    )
  AND a.court_no = 1
  AND a.ci_cri = 2
  AND a.status = 'P'
GROUP BY
  b.filing_no
ORDER BY
  a.dt_of_filing DESC
LIMIT
  0, 2000
4

1 回答 1

0

问题是一个子查询 -

SELECT purpose_code FROM Daily_proc
WHERE filing_no = a.filing_no AND next_date = max(next_date)

试试这个查询 -

SELECT
  purpose_code
FROM
  Daily_proc
WHERE
  filing_no = 20 AND next_date = (SELECT MAX(next_date) FROM Daily_proc);

创建表:

CREATE TABLE A(
  filing_no INT,
  pet_name VARCHAR(20),
  res_name VARCHAR(20),
  court_no INT);
INSERT INTO A VALUES
  (1, 'xyz', 'PQR', 1),
  (2, 'abc', 'def', 2);

CREATE TABLE B(
  filing_no INT,
  purpose_code INT,
  next_date DATE);
INSERT INTO B VALUES
  (2, 20, '2012-8-3'),
  (1, 21, '2012-9-3'),
  (2, 22, '2012-10-3'),
  (1, 23, '2012-11-15');

CREATE TABLE C(
  purpose_code INT,
  purpose_name VARCHAR(20));
INSERT INTO C VALUES
  (20, 'institution'),
  (21, 'summon'),
  (22, 'proceeding'),
  (23, 'order');

SELECT a.filing_no, a.pet_name, a.res_name, c.purpose_name, b.next_date FROM a
  JOIN (SELECT * FROM (
          SELECT * FROM b ORDER BY filing_no, next_date DESC
       ) t GROUP BY filing_no) b
    ON a.filing_no = b.filing_no
  JOIN c
    ON b.purpose_code = c.purpose_code
WHERE a.court_no = 1;

结果:

+-----------+----------+----------+--------------+------------+
| filing_no | pet_name | res_name | purpose_name | next_date  |
+-----------+----------+----------+--------------+------------+
|         1 | xyz      | PQR      | order        | 2012-11-15 |
+-----------+----------+----------+--------------+------------+
于 2012-11-07T07:38:03.143 回答