简体   繁体   English

在UNION SELECT中使用SQL Case合并两个没有相似字段的表

[英]Using SQL Case in a UNION SELECT to combine two tables with no like fields

I have two SQL tables (that cannot be modified, this is a question of how to get it without like columns), and I need to find out the table type when using an inner join to list the city and states: 我有两个SQL表( 无法修改,这是一个如何在没有类似列的情况下获取它的问题),并且在使用内部联接列出城市和州时,我需要找出表类型:

CREATE TABLE authors 
  ( 
  au_id    CHAR(3)     NOT NULL, 
  au_fname VARCHAR(15) NOT NULL, 
  au_lname VARCHAR(15) NOT NULL, 
  phone    VARCHAR(12)         , 
  address  VARCHAR(20)         , 
  city     VARCHAR(15)         , 
  state    CHAR(2)             , 
  zip      CHAR(5)             , 
  CONSTRAINT pk_authors PRIMARY KEY (au_id) 
  ); 

CREATE TABLE publishers 
  ( 
  pub_id   CHAR(3)     NOT NULL, 
  pub_name VARCHAR(20) NOT NULL, 
  city     VARCHAR(15) NOT NULL, 
  state    CHAR(2)             , 
  country  VARCHAR(15) NOT NULL, 
  CONSTRAINT pk_publishers PRIMARY KEY (pub_id) 
  ); 

I am attempting to use a CASE for the select to output correctly: 我正在尝试使用CASE进行选择以正确输出:

SELECT CASE
    WHEN LCASE(SUBSTR(/*suppose id*/, 0, 1)) == 'a'
    THEN 'author'
    ELSE 'publisher'
    END
AS type, city, state
FROM authors
INNER JOIN publishers

The tables are in a format such that the id's are different, but also hold different names: 这些表的格式使得ID有所不同,但名称也不同:

INSERT INTO authors VALUES('A01','Sarah','Buchman','718-496-7223', 
      '75 West 205 St','Bronx','NY','10468'); 
INSERT INTO publishers VALUES('P01','Abatis Publishers','New York','NY','USA'); 

And I'm attempting to reach an output like so: 我试图达到这样的输出:

type        |   city        |   state
--------------------------------------------------
author      |   Rochester   |   NY
author      |   Syracuse    |   NY
publisher   |   New York    |   NY

How can I effectively make a comparison between the two tables when they do not have like columns? 当两个表没有相似的列时,如何有效地进行比较? Can I call a field value on a table to check if it is null without throwing an SQL Exception? 我可以在表上调用字段值以检查它是否为null而不抛出SQL异常吗?

As there is no column to make a comparison between the two tables ie, nothing which can filter out the rows after Cartesian product, inner join won't server the purpose. 因为没有列可以在两个表之间进行比较,即没有什么可以过滤笛卡尔积之后的行,所以内部联接将无法达到目的。 It's more of like selecting records from two multi-sets and combining them. 这更像是从两个多集中选择记录并将它们组合在一起。 In T-SQL this can be achieved using Union as: 在T-SQL中,可以使用Union来实现此目的:

select 'authors' as [type]
       , city,state
       from authors
union 
select 'publishers' as [type]
       , city,state
       from publishers

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

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