There are three tables: book , video , audio , which are not united by anything. The only thing is that they all have the created_at field. How do I get data from these three tables and sort by created_at ?
- @NickVolynkin tables are not united. - Sergalas
- onewhat data and in what form to get? Maybe you need a normal union - Mike
- oneOr even union all. - Nick Volynkin ♦
- @Mike how to sort by create_at - Sergalas
- @NickVolynkin and how to sort by create_at - Sergalas
|
2 answers
select a, b, c, create_at from book union all select x, y, z, create_at from video .... order by create_at After create_at must be selected in all parts of the request. In the first select, it is required to be called exactly as it is written in order by . The number and types of columns of all parts must match (i.e., the type of column a in the example must match the type of column x ).
As an option, in the sorting one can indicate the ordinal number of the column in the selection list, i.e. order by 4
|
If the tables match the fields, then it makes sense to combine them. If the tables in the fields do not match, then three queries and form from them the resulting array, which is already sorted by the field created_at.
- If the fields do not coincide, then the necessary fields are simply selected in the necessary order, so that the union is made and the union is made. - Mike
- Meaning in a combined query, if these tables have only one field (created_at) common? - Saturn
- Preparation of the request takes the same time. one query will work faster than 3, and the selection of certain fields at the very beginning reduces the traffic from the database to the client - Mike
- Well, this is another question that will work faster, a union or some ordinary select. And about the fields, I have already said above, if the mc only has this field - created_at is the same, there is no point in such a query. Well, he gets a row with the creation date of the three tables, and then what? - Saturn
|