简体   繁体   English

从多个表中创建UNIQUE视图,其中一些字段被忽略

[英]Create UNIQUE view from multiple tables where some fields are ignored

I would like to create a view like: 我想创建一个像这样的视图:

CREATE OR REPLACE VIEW all_cities AS
 SELECT city,date_added FROM tableA
 UNION DISTINCT
 SELECT city,date_added FROM tableB
 UNION DISTINCT
 SELECT city,date_added FROM tableC;

The all_cities table should only contain unique city entries from other tables however the other tables can have the same cities added with different dates this breaks my union and going to result in having all those duplicates in my all_cities. all_cities表应该只包含其他表中的唯一城市条目,但是其他表可以在相同的城市中添加不同的日期,这会破坏我的联盟,并导致在all_cities中具有所有这些重复项。 I still want to see the date_added field from at least one of the merged results (doesn't matter which). 我仍然希望至少从合并结果之一中看到date_added字段(与哪一个无关)。

With other words: How can I create a view which creates me an unique list from 3 tables but ignoring the date_added field when it does the uniqueing. 换句话说:如何创建一个视图,该视图从3个表中创建了一个唯一列表,但是在进行惟一时忽略了date_added字段。

Thanks 谢谢

The best way for select 最好的选择方式

select city, min(date_added)
from ( 
  SELECT city,date_added FROM tableA
  UNION DISTINCT
  SELECT city,date_added FROM tableB
  UNION DISTINCT
  SELECT city,date_added FROM tableC
)A
GROUP BY city

but MySQL doesn't allow to use sub queries in view statement, however you can use view in view statement, so I would go for this solution with 2 views. 但是MySQL不允许在view语句中使用子查询,但是您可以在view语句中使用view,因此我将为该解决方案提供2个视图。

CREATE OR REPLACE VIEW all_cities_support_view AS
SELECT city,date_added FROM tableA
UNION DISTINCT
SELECT city,date_added FROM tableB
UNION DISTINCT
SELECT city,date_added FROM tableC;

CREATE OR REPLACE VIEW all_cities AS
SELECT city, min(date_added) as date_added
FROM all_cities_support_view 
GROUP BY city;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM