mysql - 如何使用子查询显示来自多个表的列名

标签 mysql sql database

我创建了下表并插入了这些值:

create table customer (cid int, cname varchar(25), email varchar(25), phone int, status varchar(25), primary key (cid));
create table accounts( cid int, account int, atype varchar(25), balance int, foreign key(cid) references customer(cid));
create table address( cid int, street varchar(25), city varchar(25), country varchar(25), foreign key(cid) references customer(cid));




insert into customer values (101,'A', 'a@gmail.com', 99,'active');
insert into accounts values (101, 123, 'SA', 1000);
insert into address values (101, 'HMT','Blore','India');

insert into customer values (102,'B', 'b@gmail.com', 199,'active');
insert into accounts values (102, 123, 'CA', 2000);
insert into address values (102, 'Jayanagar','Blore','India');

我的目标是显示状态为活跃的客户的 cname、帐户和余额。

我试过使用这个编写查询:(我无法使用这个打印 cname 列)但它显示了其余部分。

select account, balance
from accounts
where cid in (select cid from customer where status = 'active');

这不起作用:

select cname, account, balance
from  customer, accounts
where cid in (select cid from customer where status = 'active');

最佳答案

一种可能的方法是在公共(public)客户 ID 上连接两个表。

SELECT c.cname,
       a.account,
       a.balance
       FROM customer c
            LEFT JOIN accounts a
                      ON a.cid = c.cid
       WHERE c.status = 'active';

关于mysql - 如何使用子查询显示来自多个表的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57335374/

相关文章:

mysql - 使用多个键在一个查询中插入和更新

sql - sql中是否有一个函数可以找到表中的第二个最小值,然后在情况下使用

sql - 如何从描述中提取数字(价格)

python - 使用Python类将数据写入xls

c# - 如何在 C# 中将 mySQL NULL 值转换为整数 0?

php - 使用 PHP MySQL(向上/向下按钮)手动排序?

c# - GROUP BY、ORDER BY 和 LINQ 中的第一

database - 内部排序,使用两个堆解释的锦标赛排序算法

mysql - 添加另一个数据库还是不添加另一个数据库,这就是问题

php - mySql 获取数组忽略空值