Postgres - 如何连接表没有重复

时间:2018-04-11 21:53:12

标签: django postgresql sqlite duplicates

我正在开发一个本地使用SQLite的项目,现在转移到PostGres(On Heroku)时,我的查询报告错误" r.social必须出现在GROUP BY子句中或用于聚合函数"

原始查询是:

SELECT  DISTINCT c.name, r.social, c.description, p.price
            FROM cryptomodels_coin c  
            LEFT JOIN cryptomodels_coinprice p
            ON  p.coin_id  =  c.name
            LEFT JOIN cryptomodels_CoinRating r 
            ON r.coin_id = c.name
            GROUP BY c.name

本地工作正常,每个硬币返回一个唯一的行

当我将此添加到PostGres环境时,它抛出了上面提到的聚合函数错误 - 我设法通过将所有列添加到" Group by"来解决这个问题。条款,如下所示:

   SELECT  DISTINCT c.name, r.social, c.description, p.price
                FROM cryptomodels_coin c  
                LEFT JOIN cryptomodels_coinprice p
                ON  p.coin_id  =  c.name
                LEFT JOIN cryptomodels_CoinRating r 
                ON r.coin_id = c.name
                GROUP BY c.name, r.social, c.description, p.price

问题是我现在每个硬币都有重复的行

我已经做了很多阅读并尝试了很多解决方案,其中一些会抛出错误而另一些仍会导致重复行,真的不知道如何继续,谢谢你的帮助

编辑以获取更多信息: 每个硬币都有很多价格和众多评级,其中的cryptomodels_coin表格被其他表格引用,其名称为" coin_id"这三个硬币例如:

Coin table: 
| Name | 
--------
|  0X  |
| XSV  | 
| BTC  |

Price table: 
| Coin_id | Price |
-------------------
| 0X      |  43.2 |
| XSV     |  20.0 |
| BTC     |  99999| 

Rating table:
| Coin_id | Social|
-------------------
| 0X      | 20,000|
| XSV     | 12,000|
| BTC     | 5,0000| 

编辑2:

 CREATE TABLE "cryptomodels_coin" (
 "name" varchar(200) NOT NULL PRIMARY KEY, 
 "description" text NOT NULL);

CREATE TABLE "cryptomodels_coinprice" (
 "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, 
 "price" real NULL, 
 "coin_id" varchar(200) NOT NULL REFERENCES "cryptomodels_coin" ("name") );

CREATE TABLE "cryptomodels_coinrating" (
 "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, 
 "social" text NULL, "coin_id" varchar(200) NOT NULL REFERENCES "cryptomodels_coin" ("name"));

添加了SQLFiddle: http://sqlfiddle.com/#!15/9fcff/1 谢谢!

1 个答案:

答案 0 :(得分:0)

我想这样的事情会消除你想要的重复:

SELECT c.name AS name, 
       r.social AS social, 
       c.description AS description, 
       SUM(p.price) AS price
FROM cryptomodels_coin c  
LEFT JOIN cryptomodels_coinprice p ON  p.coin_id  =  c.name
LEFT JOIN cryptomodels_CoinRating r ON r.coin_id = c.name
GROUP BY c.name,r.social,c.description