MYSQL select same column name as alias in union not working

Michael Samuel

I have a simple MYSQL query that unions two tables:

SELECT * FROM (
    SELECT col1 AS col1A FROM table1
    UNION 
    SELECT col1 AS col1B FROM table2
) AS t WHERE col1A <> col1B

I have a column called col1 in both tables and I need to select only rows that have a different value of that column so I select them as aliases. When I run this query I got:

Unknown column 'col1B' in 'where clause'

Table1 data:

col1
----
test

Table2 data:

col1
----
test

The query should return no rows as each value in col1 in table1 is equal to each value in col1 in table2 instead it returns that col1 in table2 is unknown although I select it as an alias

spencer7593

Why Error 1054 is being returned by OP query

The error that's being returned is because the name assigned to a column from the result of a UNION is taken from the first SELECT.

You can observe this by running a simple example:

 SELECT 1 AS one 
  UNION
 SELECT 2 AS two 

The resultset returned by that query will contain a single column, the name assigned to the column will be one, the column name from the first SELECT. This explains why you are getting the error from your query.


One way to return rows with no match

To return values of col1 from table1 which do not match any value in the col1 column from table2...

one option to use an anti-join pattern...

    SELECT t1.col1
      FROM table1 t1
      LEFT
      JOIN table2 t2
        ON t2.col1 = t1.col1
     WHERE t2.col1 IS NULL

The LEFT JOIN operation returns all rows from table1, along with any "matching" rows found in table2. The "trick" is the predicate in the WHERE clause... any "matching" rows from table2 will have a non-NULL value in col1. So, if we exclude all of the rows where we found a match, we're left with rows from table1 that didn't have a match.

If we want to get rows from table2 that don't have a "matching" row in table1, we can do the same thing, just flipping the order of the tables.

If we combine the two sets, but only want a "distinct" list of "not matched" values, we can use the UNION set operator:

    SELECT t1.col1
      FROM table1 t1
      LEFT
      JOIN table2 t2
        ON t2.col1 = t1.col1
     WHERE t2.col1 IS NULL
     UNION 
    SELECT s2.col1
      FROM table2 s2
      LEFT
      JOIN table1 s1
        ON s1.col1 = s2.col1
     WHERE s1.col1 IS NULL

--

Finding out which table the non-matched value is from

Sometimes, we want to know which query returned the value; we can get that by including a literal value as a discriminator in each query.

    SELECT 'table1' AS src
         , t1.col1
      FROM table1 t1
      LEFT
      JOIN table2 t2
        ON t2.col1 = t1.col1
     WHERE t2.col1 IS NULL
     UNION 
    SELECT 'table2' AS src
         , s2.col1
      FROM table2 s2
      LEFT
      JOIN table1 s1
        ON s1.col1 = s2.col1
     WHERE s1.col1 IS NULL
    ORDER BY 2

A different (usually less performant) approach to finding non-matching rows

An entirely different approach, to returning an equivalent result, would be do something like this:

SELECT q.col1
  FROM ( SELECT 't1' AS src, t1.col1 FROM table1 t1 
          UNION
         SELECT 't2' AS src, t2.col1 FROM table2 t2
       ) q
 GROUP BY q.col1
HAVING COUNT(DISTINCT q.src) < 2
ORDER BY q.col1

(The inline view q will be "materialized" as a derived table, so this approach can be expensive for large sets, and this approach won't take advantage of indexes on col1 to perform the matching.) One other small difference between this and the anti-join approach: this will omit a col1 value of NULL if a NULL exists in both tables. Aside from that, the resultset is equivalent.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Column alias is not working for Group, Where and Having in MySQL

분류에서Dev

Mysql - How to Give Alias name for column

분류에서Dev

To display photos of same alias name using php and mysql

분류에서Dev

How to perform union on table when table consists of different column name but datatype is same?

분류에서Dev

mysql. select column as column1 where ... union all select column as column2 where ... column1 만보기 (column2 아님)

분류에서Dev

MySQL UNION SELECT 및 IN 절

분류에서Dev

Alias column name for Use in CASE Statement

분류에서Dev

how to select multiple same column in one column

분류에서Dev

How do I include an ampersand in the column alias name in a Oracle query

분류에서Dev

Mysql select data in same row

분류에서Dev

Working faster with variables that have almost the same name

분류에서Dev

mysql SELECT column only if exists

분류에서Dev

MySQL Select order by custom column

분류에서Dev

select sum of columns with the same name and size

분류에서Dev

how to name the column same as records of column of another table in oracle

분류에서Dev

Query a specific name within the same table (MySQL)

분류에서Dev

PHP MySQL Column Loop if name is similar?

분류에서Dev

MySQL query to get values based on same column

분류에서Dev

Calculate on alias name

분류에서Dev

PHP mysql select data where column array

분류에서Dev

MySQL Select from column use ^ as delimiter

분류에서Dev

PHP MySQL select data where in column array

분류에서Dev

PHP MySQL select data where in column array

분류에서Dev

php mysql SELECT AS with WHERE Column not found?

분류에서Dev

Combine two column as new and use that column in the same mysql query

분류에서Dev

OPENROWSET with no column alias?

분류에서Dev

SQL(MYSQL) Select column names where sum of that column > 0

분류에서Dev

How to use a table alias with a Union statement in Access?

분류에서Dev

How to solve my Laravel between query on same column name

Related 관련 기사

  1. 1

    Column alias is not working for Group, Where and Having in MySQL

  2. 2

    Mysql - How to Give Alias name for column

  3. 3

    To display photos of same alias name using php and mysql

  4. 4

    How to perform union on table when table consists of different column name but datatype is same?

  5. 5

    mysql. select column as column1 where ... union all select column as column2 where ... column1 만보기 (column2 아님)

  6. 6

    MySQL UNION SELECT 및 IN 절

  7. 7

    Alias column name for Use in CASE Statement

  8. 8

    how to select multiple same column in one column

  9. 9

    How do I include an ampersand in the column alias name in a Oracle query

  10. 10

    Mysql select data in same row

  11. 11

    Working faster with variables that have almost the same name

  12. 12

    mysql SELECT column only if exists

  13. 13

    MySQL Select order by custom column

  14. 14

    select sum of columns with the same name and size

  15. 15

    how to name the column same as records of column of another table in oracle

  16. 16

    Query a specific name within the same table (MySQL)

  17. 17

    PHP MySQL Column Loop if name is similar?

  18. 18

    MySQL query to get values based on same column

  19. 19

    Calculate on alias name

  20. 20

    PHP mysql select data where column array

  21. 21

    MySQL Select from column use ^ as delimiter

  22. 22

    PHP MySQL select data where in column array

  23. 23

    PHP MySQL select data where in column array

  24. 24

    php mysql SELECT AS with WHERE Column not found?

  25. 25

    Combine two column as new and use that column in the same mysql query

  26. 26

    OPENROWSET with no column alias?

  27. 27

    SQL(MYSQL) Select column names where sum of that column > 0

  28. 28

    How to use a table alias with a Union statement in Access?

  29. 29

    How to solve my Laravel between query on same column name

뜨겁다태그

보관