A
A
Alexander Ivanov2021-08-15 12:13:50
MySQL
Alexander Ivanov, 2021-08-15 12:13:50

How to search across different tables with different fields?

I do a search on the site, which searches for 4 tables, news, users, posts, summaries. respectively in each table the fields. prompt how to make request under these four tables with different fields.
I only have enough brains to use left join through union, it doesn’t work because when searching for four tables, sql gives an error that the answer has a different number of fields. how to make a request?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Page-Audit.ru, 2021-08-15
@cyberchainik

Through UNION.
When selecting SELECT, use not the * symbol, but specific fields (for example, id, name, etc.), which you rename through an alias.

SELECT `id` AS 'field1', `name` AS `field2`, `other` AS `field3` FROM `table1`
UNION
SELECT `uid` AS 'field1', `title` AS `field2`, `again_other` AS `field3` FROM `table2`
UNION
...

as a result, get a table with the same number of columns, which you then use.
If there is no field in the table, then try using a combination of type "" AS `fieldN` or NULL AS `fieldN` for alignment.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question