简体   繁体   中英

How do I combine the results of two queries in SQL?

My bad if I don't understand simple things, as I am just beginning to write SQL queries.

I have two queries:

SELECT * FROM status WHERE author IN (SELECT user1 FROM friends WHERE user2='$username' AND accepted='1') OR author IN (SELECT user2 FROM friends WHERE user1='$username' AND accepted='1')

and

SELECT * FROM status WHERE author = '$username'

How can I combine the results of these two queries, either natively in the SQL query, or in PHP?

Try UNION :

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

To allow duplicate values, use the ALL keyword with UNION.

SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

What's wrong with just using OR ?

SELECT * 
FROM status 
WHERE author IN (SELECT user1 FROM friends WHERE user2='$username' AND accepted='1') 
    OR author IN (SELECT user2 FROM friends WHERE user1='$username' AND accepted='1')
    OR author = '$username'

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