Forum Moderators: open
Example: (much simplified)
Table: Articles
Fields:
ArticleID
AuthorID
PublisherID
ArticleTitle
ArticleText
DatePublished
Table: Users
Fields:
UserID
Username
FirstName
LastName
Both AuthorID and PublisherID represent rows in the Users table.
I am trying to display full information about the article, its author and its publisher on a page. I am wondering if there's any automatic way to alias all columns joined from Users without explicitly writing each one of them in the query (as I have a lot more columns than in the example above and this is quite unwieldy). Something like:
SELECT A.*, U1.* AS 'U1_*', U2.* AS 'U2_*' FROM Articles AS A LEFT JOIN Users AS U1 ON A.AuthorID = U1.UserID LEFT JOIN Users AS U2 ON A.PublisherID = U2.User ID WHERE Articles.DatePublished = '2006-02-02'
To the best of my knowledge there is no ANSI standard for aliasing columns the way you are requesting. The columns would all be returned still, of course. For example,
CREATE TABLE table1 (
tid INTEGER,
price DECIMAL(4,2)
);
CREATE TABLE table2 (
tid INTEGER
);
INSERT INTO table1 (tid, price) VALUES(1,11.11), (2,22.22);
INSERT INTO table2 (tid) VALUES(1), (2);
SELECT T1.*, T2.* FROM table1 AS T1, table2 AS T2;
--
-- Returns:
--
+------+-------+------+
¦ tid ¦ price ¦ tid ¦
+------+-------+------+
¦ 1 ¦ 11.11 ¦ 1 ¦
¦ 2 ¦ 22.22 ¦ 1 ¦
¦ 1 ¦ 11.11 ¦ 2 ¦
¦ 2 ¦ 22.22 ¦ 2 ¦
+------+-------+------+
Yes, that works as described. However PHP allows me to grab columns out of rows returned either by their order (1,2,3,etc) or their name ('tid', 'price'). By name the second tid column overwrites the values of the first (and thus I get a table with just 2 columns). By numeric order would work, however I am very wary of using that because any column addition / deletion would upset it very very easily.
Of course, this all gets more complicated when dealing with joined tables which is where I am at now in the process of writing this stuff.
Let me know if you'd like to see the code I have so far.