如何在sql中进行查询,让人拥有更多房屋?

问题描述 投票:0回答:3

我有2张桌子,房子和客户,一个客户可以有很多房子,但房子只属于一个客户,我需要一个查询,给我拥有更多房屋的人,我该怎么办?我知道如何做一个Count(*)和一个Max但我不能建立正确的方式来给我想要的东西

表房子ID价格地址Id_client

客户ID名称

mysql sql postgresql sqlite
3个回答
2
投票

您可以使用以下内容: -

SELECT clients.id, clients.name, count(id_client) AS houses_owned FROM house JOIN clients ON id_client = clients.id 
GROUP BY id_client 
ORDER BY count(id_client) DESC LIMIT 1;

但是,如果许多客户拥有相同数量的最拥有的房屋,那么只返回其中一个。

例如,考虑以下测试示例(): -

DROP TABLE IF EXISTS house;
DROP TABLE IF EXISTS clients;
CREATE TABLE IF NOT EXISTS house (id INTEGER PRIMARY KEY, address TEXT, id_client INTEGER);
CREATE TABLE IF NOT EXISTS clients (id INTEGER PRIMARY KEY, name);
INSERT INTO clients (name) VALUES ('Fred'),('Mary'),('Tom'),('Jane');
INSERT INTO house (address,id_client) VALUES 
    ('House 1',3),('House 2', 1),('House 3',2),('House 4',1),('House 5',3);
SELECT clients.id, clients.name, count(id_client) AS houses_owned FROM house JOIN clients ON id_client = clients.id 
GROUP BY id_client 
ORDER BY count(id_client) DESC LIMIT 1;

结果将是: -

enter image description here

然而,汤姆还拥有2间房屋,取消了LIMIT 1条款,结果如下:

enter image description here


2
投票

正如评论中所建议的那样,这可以使用子选择来完成。子选择将获取所有客户端以及他们每个人拥有的房屋数量,然后由拥有最多房屋的客户订购。然后主要选择将从中获取第一个结果(使用limit 1)以找出哪个客户拥有最多的房屋。

select
sub.id,
sub.name,
sub.count
from (
    select clients.id, count(houses.id) as count
    from clients
    inner join houses on
    clients.id = houses.id_client
    group by houses.id_client
    order by count desc
) as sub
limit 1;

2
投票

该查询将返回拥有最多房屋数量的所有所有者(即,如果3个所有者都拥有5个房屋,并且5是任何客户拥有的房屋的最大数量,则将返回所有房屋)。它将clients连接到每个客户拥有的房屋数量表,然后将该数字与任何客户拥有的最大房屋数量进行比较(WHERE子句中的子查询):

SELECT c.name, h.houses_owned
FROM clients c
JOIN (SELECT id_client, COUNT(*) AS houses_owned 
      FROM houses
      GROUP BY id_client) h
  ON h.id_client = c.id
WHERE h.houses_owned = (SELECT COUNT(*) AS houses_owned 
                        FROM houses
                        GROUP BY id_client
                        ORDER BY houses_owned DESC
                        LIMIT 1)

SQLFiddle Demo(感谢@MikeT的数据)

© www.soinside.com 2019 - 2024. All rights reserved.