views:

61

answers:

3

I am working on a database join and I want to do the following:

Select tabel_one.id, 
       tabel_one.title, 
       tabel_one.content, 
       table_two.value as table_two.key 
  from tabel_one 
  Join table_two ON table_two.id = table_one.id ....

The Important part is:

table_two.value as table_two.key

Is there a way this could work?

+3  A: 

No, you cannot define an alias referencing a table.

In general, you should simply use:

table_two.value as key

Otherwise, as OMG Ponies suggested in another answer, you can wrap the alias in backticks:

table_two.value as `table_two.key`
Daniel Vassallo
Well, that does not work. To specifiy: I have a table with posts and a table with data for this posts. The data table ist the one joined.The structure of this one is:´id ; post_id ; type ; value´but type could be 'tags' or 'author' you never know.So I want to join 'post_data.value as post_data.type'.post_data.type must of course be not written, but be 'tags' or 'author'. Did I understand you correct, that this is impossible?
Lukas Oppermann
Nope, I still don't understand the question.
MJB
@Lukas The column names are fixed for all rows in the result set. You can have one set with tags and a separate set with author or even one with tags and author (with only one non-NULL) using appropriate logic.
Cade Roux
+1  A: 

This:

Select tabel_one.id, 
       tabel_one.title, 
       tabel_one.content, 
       table_two.value as `table_two.key` 
  from tabel_one 
  Join table_two ON table_two.id = table_one.id

...works for me on MySQL 5.1.35. Because of the period, you need to enclose the alias with backticks

OMG Ponies
+1... Good idea :)
Daniel Vassallo
A: 

Judging by your comment on this answer, I expect what you really want is:

Select tabel_one.id,  
       tabel_one.title,  
       tabel_one.content,  
       table_two.value as tags,
       table_three.value as author
  from table_one  
  LEFT Join table_two ON table_two.id = table_one.id 
  AND table_two.key= 'tags'
  LEFT Join table_three ON table_three.id = table_one.id 
  AND table_three.key= 'author'
Cade Roux
Well, not quite, because firstly, author and tags are bot in the same table and secondly, you never know which one is in the table. I am going to use a different method though. Thanks anyway.
Lukas Oppermann