Looking to create a subquery that displays only one column MYSQL

自古美人都是妖i 提交于 2019-12-11 19:04:45

问题


This database is for a book loan system. Where if a student takes a copy of a book the system accepts there student number and gives them a return date for the book. These are the two tables I am using

loan table:

 CREATE TABLE loan (
    `code` INT NOT NULL,
    `no` INT NOT NULL,
    taken DATE NOT NULL,
    due DATE NOT NULL,
    `return` DATE NULL,
    CONSTRAINT pri_loan PRIMARY KEY (taken),
    CONSTRAINT for_loan 
        FOREIGN KEY (`code`) REFERENCES copy (`code`),
        FOREIGN KEY (`no`) REFERENCES student (`no`));

student table:

CREATE TABLE student (
`no` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
school CHAR(3) NOT NULL,
embargo BIT NOT NULL,
CONSTRAINT pri_student PRIMARY KEY (`no`));

Firstly I am looking to calculate the latest due date for a book copy (it will bring up the code for the book and when the latest due date for that book is) which I have done by using this code which worked perfectly

SELECT `code`, max(due)
FROM loan
    GROUP BY `code`

Now I want to modify this query so that it fetches the latest due dates for each book but will only display the student number (no) that has the book. To do this I need to use a sub query which I know very little about as I am only starting to use MySQL. Basically im unsure how to create this sub query and I am wondering if someone can help me out and also explain it not just show me the code.


回答1:


What you're looking for is the HAVING syntax:

SELECT
    `no` as student
FROM
    `loan`
GROUP BY
    `code`
HAVING
    DATETIME(`due`) = MAX(DATETIME(`due`));

HAVING lets you add a condition to a SELECT statement that references and filters by the available values (including selected columns and their final values, which can be really handy if you're doing calculations).

See here for more info: https://www.guru99.com/group-by.html



来源:https://stackoverflow.com/questions/52992795/looking-to-create-a-subquery-that-displays-only-one-column-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!