Richard Sweeney
Richard Sweeney

Reputation: 782

mySQL select columns from different tables

1000 Apologies if I've repeated a question, couldn't find an answer here to my question.

I'm try to retrieve the data from 2 separate columns from 2 unrelated tables in the same query.

I've tried using a UNION statement, but the problem is that I need to be able to separate the results into 'venues' and 'programmes' - here was what I did:

SELECT venue_name
FROM my_venues
UNION
SELECT programme_title
FROM my_programmes;

Maybe it's not necessary to combine the query and I can just do 2 separate queries? The database won't be especially large, but it seems unnecessary...

Help and thanks!

Upvotes: 1

Views: 3945

Answers (1)

Konerak
Konerak

Reputation: 39763

Just add a constant column in both selects, with the same name, but different values:

SELECT "venues"  as source, venue_name as thing_name
FROM my_venues
UNION ALL
SELECT "programmes"  as source, programme_title as thing_name
FROM my_programmes;

Now:

  • Rows with value "venues" for column source will come from the table my_venues ,
  • rows with value "programmes" for column source will come from table my_programmes.

Upvotes: 1

Related Questions