I'm trying to select from multiples tables(10+) that are in the following format using mySQL.
+----------table(n)-----------+
+-----------------------------+
| url | id | ... |
+-----------+-----------+-----+
| url1.com | 12345678 | ... |
| url2.com | 45832458 | ... |
What I need to do is retrieve the id from each table for a given URL and return it in a single row like so.
+--------------table(n)--------------+
+------------------------------------+
| url | table(n) | table(n+1) |
+-----------+-----------+------------+
| url1.com | 12345678 | 8182735 |
But the URL might not exist for a given table, so I just need to retrieve all the ids from the tables where the URL is found.
For example, I have 10 tables and a URL/id is in 4 of them. I need to retrieve these 4, in a single row. I've tried to use aliases for columns along with various JOIN combinations to no avail.
Any help would be appreciated.
You can do this with a union all
and group by
:
select url,
max(id1) as id1, max(id2) as id2, . . .
from ((select url, id as id1, NULL as id2, . . . from table1) union all
(select url, NULL as id1, id as id2, . . . from table1) union all
. . .
) t
group by url;
try like this
SELECT tu.URL,COALESCE(table_1.id,0) AS table_1,COALESCE(table_2.id,0) As
table_2,......,COALESCE(table_n.id,0) AS table_n FROM Table_URL tu
LEFT JOIN table_1 ON tu.URL = table_1.URL
LEFT JOIN table_2 ON tu.URL = table_2.URL
.
.
LEFT JOIN table_n ON tu.URL = table_n.URL
You want a variable number of columns generated by your SQL statement, and you cannot do that with MySQL.
You can see some techniques to get around it here: MySQL pivot row into dynamic number of columns
Many reporting tools will let you do things like you want to, but using some sort of prepared statement hack with MySQL would be the only way to do it:
http://buysql.com/mysql/14-how-to-automate-pivot-tables.html
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.