简体   繁体   English

MySQL 如何使用外键标识另一个表中的列?

[英]MySQL How do I use a foreign key to identify a column in another table?

I am trying to get the name of the customer who has the largest remaining principal.我正在尝试获取拥有最大剩余本金的客户的名称。

In my DB loans.customer_id is a foreign key referring to customers.customer_id ;在我的数据库loans.customer_id是一个外键,指的是customers.customer_id

These are the create statements:这些是创建语句:

    CREATE SCHEMA IF NOT EXISTS `mortgages` DEFAULT CHARACTER SET utf8 ;

USE mortgages ;使用mortgages

    CREATE TABLE IF NOT EXISTS `mortgages`.`customers` (
      `customer_id` INT NOT NULL AUTO_INCREMENT,
      `customer_name` VARCHAR(100) NULL,
      `customer_address` VARCHAR(200) NULL,
       `customer_email` VARCHAR(100) NULL,
      PRIMARY KEY (`customer_id`))
     ENGINE = InnoDB;


    CREATE TABLE IF NOT EXISTS `mortgages`.`loans` (
      `loan_id` INT NOT NULL auto_increment,
      `original_principal` DOUBLE NULL,
      `remaining_principal` DOUBLE NULL,
      `princiapl_paid` DOUBLE AS (original_principal - remaining_principal),
       `interest_paid` DOUBLE NULL,
      `customer_id` INT NOT NULL,
      PRIMARY KEY (`loan_id`),
      INDEX `fk_loans_customers_idx` (`customer_id` ASC) VISIBLE,
      CONSTRAINT `fk_loans_customers`
        FOREIGN KEY (`customer_id`)
        REFERENCES `mortgages`.`customers` (`customer_id`)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION)
    ENGINE = InnoDB;

These are the insert statements I used:这些是我使用的插入语句:

 INSERT INTO customers VALUES
    (default, 'Joe', '1313 Mockingbird Ln, Transylvania, PA 19666', 
    'jsmith@munsters.com'),
    (default, 'Jane', '123 Heaven Blvd, Cloud City, MA 00911', 'doejd@aol.com'),
    (default, 'Mike', '230860, Club Rd., New York City, NY 10108', 'mikejones@nightclub.com'), 

     INSERT INTO loans VALUES
    (default, 245000.00, 198232.21, default, 21833.25, 1),
    (default, 708921.50, 551123.80, default, 880082.99, 2),
    (default, 99000.00, 1001.12, default, 4591.12, 3),

I have tried:我努力了:

SELECT customers.customer_name, loans.customer_id
from customers, loans
where (loans.remaining_principal=(SELECT MAX(loans.remaining_principal) FROM loans))

this displays ALL of the customer names next to customer_id of the MAX这将显示 MAX 的customer_id旁边的所有客户名称

What I want is to display ONE customer name, who has the customer_id of the MAX我想要的是显示一个客户名称,其customer_id ID 为 MAX

What I'm getting is:我得到的是:

customer_name顾客姓名 customer_id客户ID
Joe 2 2
jane 2 2
Mike麦克风 2 2

What I want to get is:我想要得到的是:

customer_name顾客姓名 customer_id客户ID
jane 2 2

You did a cross join that combines every row from the customers with every row from the loans, so of course there's also a row for every customer combined with the maximum loan.你做了一个交叉连接,将客户的每一行与贷款的每一行结合起来,所以当然每个客户也有一行与最大贷款相结合。

Use a proper inner join instead to just combine the loans and customers which actually belong together.而是使用适当的内部连接来组合实际属于一起的贷款和客户。

SELECT co.customer_name,
       lo.customer_id
       FROM customers co
            INNER JOIN loans lo
                       ON lo.customer_id = co.customer_id
       WHERE lo.remaining_principal = (SELECT max(li.remaining_principal)
                                              FROM loans li);

db<>fiddle db<>小提琴

The WHERE clause can stay like it is, though it'll give you more than one customer should there be more than one customer sharing the same maximum loan. WHERE子句可以保持原样,但如果有多个客户共享相同的最大贷款,它会为您提供多个客户。 I don't know, if you want that or what the secondary criteria to chose one customer from them would be then, so I cannot address this further.我不知道,如果你想要这样,或者从他们那里选择一个客户的次要标准是什么,所以我无法进一步解决这个问题。

You can accomplish this with a couple sub-queries:您可以通过几个子查询来完成此操作:

SELECT customer_name, customer_id
FROM customers
where customer_id = (
    SELECT customer_id FROM loans WHERE remaining_principal = (
        SELECT MAX(remaining_principal) FROM loans))

You can simply:您可以简单地:

SELECT loans.customer_id, customers.customer_name
FROM loans
JOIN customers 
ON loans.customer_id = customers.customer_id
WHERE (loans.remaining_principal = (SELECT MAX(loans.remaining_principal) FROM loans));

JOIN lets you grab that name from the customers table as an add-on to the main data which is the loans table. JOIN 允许您从客户表中获取该名称,作为主要数据(即贷款表)的附加组件。

SELECT MAX(remaining_principal),customer_name,customer_id FROM Customers

I hope this helps.我希望这有帮助。 Also Try to avoid principle_paid = original_principal - remaining_principal , It's remaining_principal = original_principal - principle_paid还要尽量避免principle_paid = original_principal - remaining_principal ,它是remaining_principal = original_principal - principle_paid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在mysql的另一个表中编辑唯一的列引用作为外键? - How do I edit a unique column reference as foreign key in another table in mysql? 如何在一个表中使用两次列,以显示另一个表中两个外键列的关联值? - How do I use a column in one table twice, to show the associated values of two foreign key columns in another table? 如何将主键放入另一个表的外键中? PHP,MySQL - How Do I Grab And Put Primary Key Into Foreign Key In Another Table? PHP, MySQL 如何将一个表的主键值插入另一个表的外键列? - How do I insert primary key value from one table to foreign key column in another? 如何将主键作为外键插入另一个表? - How do I insert the primary key to another table as foreign key? 如何在MySQL的另一个表中仅选择没有相应外键的行? - How do I select only rows that don't have a corresponding foreign key in another table in MySQL? 如何在mysql中为外键列设置默认值 - How do I set default value for a foreign key column in mysql 在MySQL中,如何创建带有外键的列? - In MySQL, how do I create a column with a foreign key? 如何在MySQL中使列不为空并成为外键 - How do I make a column not null and be a foreign key in MySQL 如何在MySQL中更改表中的主键和表中的外键的列? - How to alter a column which is a primary key in the table and a foreign key in another table in MySQL?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM