mysql - PostgreSQL - 创建 View 时需要帮助

标签 mysql sql postgresql select view

我在这里创建一个 View 。

这是一个例子。

表 1:

time,date,label,count
12:00 AM,1-Jan,A,10
12:30 AM,1-Jan,A,10
1:00 AM,1-Jan,A,19
1:30 AM,1-Jan,B,14
2:00 AM,1-Jan,B,18
2:30 AM,1-Jan,B,13
3:00 AM,1-Jan,C,20
3:30 AM,1-Jan,C,16
4:00 AM,1-Jan,C,12
4:30 AM,1-Jan,D,10
5:00 AM,1-Jan,D,16
5:30 AM,1-Jan,D,18

表 2:

label,category
A,Apple
B,Ball
C,Cat
E,Elephant

View :

time,date,label,category,count
12:00 AM,1-Jan,A,Apple,10
12:30 AM,1-Jan,A,Apple,10
1:00 AM,1-Jan,A,Apple,19
1:30 AM,1-Jan,B,Ball,14
2:00 AM,1-Jan,B,Ball,18
2:30 AM,1-Jan,B,Ball,13
3:00 AM,1-Jan,C,Cat,20
3:30 AM,1-Jan,C,Cat,16
4:00 AM,1-Jan,C,Cat,12
4:30 AM,1-Jan,D,   ,10
5:00 AM,1-Jan,D,   ,16
5:30 AM,1-Jan,D,   ,18

查看脚本:

CREATE OR REPLACE VIEW queue_interval_wise AS 
SELECT
    t1.Time,
    t1.Date,
    t1.Label,
    t2.Category,
    t1.Count
FROM Table1 t1, Table2 t2
WHERE t1.Label = t2.Table2

当我运行该脚本时,我得到的行数多于 Table1 中的行数。

无论我使用 WHERE 子句还是 LEFT JOIN 结果都与 Table1 的行数不匹配。

有人让我知道我哪里做错了。

最佳答案

试试这个:

CREATE OR REPLACE VIEW queue_interval_wise AS 
SELECT DISTINCT 
    t1.Time,
    t1.Date,
    t1.Label,
    IFNULL(t2.Category, ''),
    t1.Count
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.Label = t2.Label

关于mysql - PostgreSQL - 创建 View 时需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20917960/

相关文章:

mysql - 如何在 mysql 或 postgresql 中唯一标识来自 information_schema 的列?

python - SQL mycursor.execute INSERT 代码使用 python 失败

php - 返回组中的所有行

mysql - 如果另一个表 B 在 mysql 中有行,则选择表 A 中的所有行

C# ADO.Net 到 db2 iseries - 连接无效

postgresql - docker Postgres Liquibase

php - Yii2 中的 Gii CRUD 生成连接表关系

php - Joomla 出于什么安全原因添加表格前缀?

sql - 是自己做唯一约束还是作为主键?

ruby-on-rails - 用于具有预定义值的多选的 Rails 4 字段类型