G
G
GlukFree2019-07-31 18:08:59
SQL
GlukFree, 2019-07-31 18:08:59

Row aliases in sql?

Hey!
There is a request:

Select * 
FROM calendar_year as cal
LEFT JOIN album as alb ON alb.year = cal.year AND (alb.band_id = 388)
WHERE cal.year BETWEEN 1969 AND 1982

The received join has 2 columns with the same name "year", obtained from different tables - album and calendar_year
Question:
How can I set aliases for the columns "year" for the already received join? I would like to output the number of values ​​in the year column using a query
SELECT COUNT(ooo.year)
FROM
(Select *
FROM calendar_year as cal
LEFT JOIN album as alb ON alb.year = cal.year AND (alb.band_id = 388)
WHERE cal.year BETWEEN 1969 AND 1982) as ooo

But it gives the error "ERROR: ambiguous reference to the column "year"", which is logical, because the table has 2 columns with the same name

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
irishmann, 2019-07-31
@GlukFree

Something like this

SELECT 
  COUNT(ooo.year_alb)
FROM
  (
  SELECT
    alb.year AS	year_alb,
    cal.year AS year_cal
  FROM
    calendar_year cal
    LEFT JOIN album alb ON alb.year = cal.year AND (alb.band_id = 388)
  WHERE 
    cal.year BETWEEN 1969 AND 1982
  ) ooo

year - column name should be enclosed in quotes, `year` - like this for MySQL, or like this "year" for PostgreSQL

K
Konstantin Tsvetkov, 2019-07-31
@tsklab

Remove *and list all required columns in the formatтаблица.столбец

R
Ruslan., 2019-07-31
@LaRN

like this for example:
select alb.year as year1, cal.year as year2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question