两个子查询之间的AND操作

时间:2018-07-22 16:51:09

标签: sql database

这些是我的表格:https://ibb.co/mqX6wy

我试图找到在银行既有贷款又有帐户的所有客户。

我正在使用MYSQL(PHP myadmin客户端)

查询应返回 Hayes,Jones,Smith

Select customer_name 
  from (
    SELECT borrower.customer_name 
      FROM borrower, loan 
      WHERE borrower.loan_number = loan.loan_number) 
        AND (SELECT depositor.customer_name 
               FROM depositor,account 
               WHERE depositor.account_number = account.account_number)

执行以上查询会引发:

Error: *#1064 - You have an error in your SQL syntax; check the manual 
that corresponds to your MariaDB server version for the right syntax to use
near 'AND  (SELECT depositor.customer_name FROM depositor,account WHERE 
depositor.acco' at line 1*

3 个答案:

答案 0 :(得分:1)

根据您的表结构,我认为您需要在查询下面

    Select t1.customer_name from 
    (
     SELECT b.customer_name FROM borrower b inner join
     on loan l b.loan_number = l.loan_number) as t1 
     inner join

    (
   SELECT depositor.customer_name FROM depositor d inner join account a on 
   d.account_number = a.account_number
    ) t2
    on t1.customer_name=t2.customer_name 

答案 1 :(得分:0)

检查完共享表的结构后,以下查询将为您工作...

  

SELECT customer_name FROM((选择借款人.customer_name FROM   借款人INNER JOIN贷款ON借款人(loan_number =贷款.loan_number)   UNION(从存款人INNER JOIN中选择depositor.customer_name   帐户ON depositor.account_number = account.account_number))

您可以根据需要尝试在这两个查询之间进行内部联接...

  

SELECT customer_name FROM((选择借款人.customer_name FROM   借款人INNER JOIN贷款ON借款人(loan_number =贷款.loan_number)   AS bl INNER JOIN(从depositor INNER选择SELECT depositor.customer_name   在JOIN账户上开户depositor.account_number = account.account_number))   AS da ON bl.customer_name = da.customer_name

答案 2 :(得分:0)

首先,当您的所有借款人都有一个贷款编号,而您的所有储户都有一个帐号时,我看不到加入的意义。假设是这种情况,您可以使用以下方法获取两个表的交集。

(SELECT customer_name FROM borrower) INTERSECT (SELECT customer_name FROM depositor)

如果不是这种情况,您仍然可以使用

(SELECT DISTINCT borrower.customer_name FROM borrower, loan WHERE borrower.loan_number = loan.loan_number) INTERSECT (SELECT DISTINCT depositor.customer_name FROM depositor,account WHERE depositor.account_number = account.account_number)

请注意使用DISTINCT来避免重复值(例如:琼斯在borrowerdepositor上都出现两次)