简体   繁体   中英

Combining and sorting result of two different SQL queries

I have two tables containing two different kinds of comments. One of the tables contain comments from users (so it has a foreign key containing their user ID), and the other table holds comments from non-logged in users (so it doesn't have any user ID, but instead it contains a name, an email, etc.)

Now when I need to print these comments I want them in the same list, ordered by their created_at value. So I need to do two different queries (the first also joins with the user table, to find usernames, etc.) and then combine the results.

I was thinking I could do a UNION, but that won't work when the tables have different fields. I could do it in my application logic by merging the two resulting arrays, but that seems messy if there's a nicer solution that can be done directly in the database.

You can still use a UNION when you align both tables by specifying the fields in the SELECT part.

Example:

Table1(id,comment,enterdate,userid)

Table2(id,comment,enterdate)

SELECT id, comment, enterdate, userid, 'Logged In' as Type FROM Table1
UNION
SELECT id, comment, enterdate, NULL, 'Guest' FROM Table2

The UNION can then be ordered as required.

the UNION sollution you suggested can be used if you name the for example the userId of the first table and the name from the second table as ex. Identity

Select userId as Identity, created_at as date from loggedUsers UNION Select name as Identity, created_at as date from guestUsers

hope that helped...

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