简体   繁体   中英

mySQL INNER JOIN very large tables with same column names

I have some big tables which I need to combine into a single very large table, to form a single-page data export for a statistical package.

This is easy with INNER JOIN but the some of the tables have the same column names and these are being overwritten by each other when I fetch them as an array in PHP.

There are 4 tables being joined with 30-200 columns in each so there are far too many field names to manually include in the query with aliases, as would be the norm in this situation.

Here's the query:

SELECT * FROM logs 
    INNER JOIN logdetail ON logdetail.logID = logs.id
    INNER JOIN clients ON clients.id = logs.clientID
    INNER JOIN records ON records.id = logdetail.id
    WHERE logs.userID=1

Is there any way around this? I don't actually mind what the column names are as long as I have the data so if I could prepend the table name to each field, that would do the trick.

I would create a view, your view would be comprised of your long query with aliases

Here is an example taken from the manual

mysql> CREATE TABLE t (qty INT, price INT);
mysql> INSERT INTO t VALUES(3, 50);
mysql> CREATE VIEW v AS SELECT qty, price, qty*price AS value FROM t;
mysql> SELECT * FROM v;
+------+-------+-------+
| qty  | price | value |
+------+-------+-------+
|    3 |    50 |   150 |
+------+-------+-------+

This has always worked for me, unless you have one to many or some other relationship among these tables, which will duplicate records.

SELECT * FROM logs l
INNER JOIN logdetail  ld ON ld.logID = l.id
INNER JOIN clients c ON c.id = l.clientID
INNER JOIN records r ON r.id = ld.id
WHERE l.userID=1

As andrew says you can also use a View to get this thing working which is much cooler.

I found a solution for this. Simply, fetch each duplicate column a second time, this time using an alias. This way, the overwritten values are selected again and aliased:

SELECT * FROM logs, 
    clients.name as clientName,
    logs.name as logName,
    etc...
INNER JOIN logdetail ON logdetail.logID = logs.id
INNER JOIN clients ON clients.id = logs.clientID
INNER JOIN records ON records.id = logdetail.id
WHERE logs.userID=1

Note: There is no need to do this for the final instance of the duplicate, because this column will not have been overwritten. So, in the example above, there is no need to include a line like records.name as recordName because, since there are no columns after it which have the same name, the record.name field was never overwritten and is already available in the name column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM