我有两张桌子“客户”和“门票”
在“门票”中,我有“ID_Client”列,其中包含:1,2,3,4,4,2值。
在“Clients”中,我有“Name”和“Surname”列,对应于“Tickets”中的ID。
查询应显示ID = 2和ID = 4
的名称和姓氏我提出了一个有效但不完整的查询:
import { Comment } from './comment';
export class Dish {
id: number;
name: string;
image: string;
category: string;
label: string;
price: string;
featured: boolean;
description: string;
comments: Comment[];
}
它返回ID = 2的Client的姓名和姓氏,但不知何故错过了ID = 4的客户端。我必须在最后添加限制1,因为没有它,它会显示ID = 2两次的客户端
答案 0 :(得分:0)
如果您只想要2行,请使用LIMIT 2
:
SELECT c.Name, c.Surname
FROM Clients c JOIN
(SELECT t.ID_Client,
FROM Tickets t
GROUP BY t.ID_Client
ORDER BY Count(*) DESC
LIMIT 2
) t
ON c.ID_Client = c.ID_Client;
答案 1 :(得分:0)
@ GordonLinoff解决方案的问题在于它需要先验知道票数表中有多少客户端具有最大条目。当数据变为1,2,3,4,4,2,3以及后来的1,2,3,4,4,2,3,4时会发生什么。根据OP初始声明,第一个之后的结果将是id = 2,3,4并且在第二个id = 4之后。需要的是一个确定SQL中必要数字的解决方案。以下是这样的。不幸的是,它是一个Oracle解决方案,我不知道MySql,但我相信它具有以下所有结构。
主要查询:
/* Final desirded columns from clients */
select name, surname
from clients
where 1=1
and id_client in
/* get id_client from ticket and assign a unique row_number for each */
(select id_client
from (select id_client
, row_number() over(partition by id_client
order by id_client) rn
from tickets
)
where 1=1
/* select only those having assigned row numbers */
and rn =
/* get the maximum rows for any id_client */
(select max(n)
from (select count(*) over(partition by id_client) n
from tickets)));
create table clients (id_client integer, name varchar2(50), surname varchar2(30));
create table tickets (id_ticket integer, id_client integer);
insert into clients (id_client, name, surname) values (1.,'Bob','Meyers');
insert into clients (id_client, name, surname) values (2.,'Bob','Adams');
insert into clients (id_client, name, surname) values (3.,'Lynn','Adams');
insert into clients (id_client, name, surname) values (4.,'William','Wallice');
insert into clients (id_client, name, surname) values (5.,'Julius','Caesar');
insert into clients (id_client, name, surname) values (6.,'William', 'Shakespeare');
insert into clients (id_client, name, surname) values (7.,'Cleopatra', 'Philopator');
insert into tickets (id_ticket, id_client)
select rownum, t
from (select 1 t from dual union all
select 2 from dual union all
select 3 from dual union all
select 4 from dual union all
select 4 from dual union all
select 2 from dual
);
RUN MAIN QUERY。
insert into tickets (id_ticket, id_client) values ((select max(id_ticket) + 1 from tickets), 3);
RUN MAIN QUERY。
insert into tickets (id_ticket, id_client) values ((select max(id_ticket) + 1 from tickets), 4);
RUN MAIN QUERY。
drop table tickets;
drop table clients;
对于Oracle老百姓我理解有更短和/或更好的解决方案,但我想在每一步显示推导。对于你MySql可能是“LIMIT(选择...)”的行,我会对解决方案感兴趣。