mysql – Simple-complex select

Question:

table: m_frend is friends with sl_frend (in example 883 is friendly with 876), BUT there are records in which other uid 's are friends with m_frend (that is, in this case, m_frend will be sl_frend ). Example 856 is friendly with 883.

mysql> select * from frends ;
+---------+----------+-------+
| m_frend | sl_frend | fr_st |
+---------+----------+-------+
|     883 |      876 |     1 |
|     880 |      875 |     1 |
|     881 |      877 |     1 |
|     856 |      883 |     1 |
|     859 |      883 |     1 |
|     860 |      883 |     1 |
|     883 |      879 |     1 |
|     883 |      880 |     1 |
|     883 |      881 |     2 |
+---------+----------+-------+
9 rows in set (0.01 sec)

In one request, in ONE POST, you need to pull out all 883 friends (those with whom 883 are friends), and THOSE WHO ARE FRIENDS WITH 883.

Such a kalmburchik came out, I hope I described the extension clearly. And is it realistic to do this (get the result in one column)?


I know what you can get first

mysql> select * from frends where m_frend=883 or sl_frend=883;
+---------+----------+-------+
| m_frend | sl_frend | fr_st |
+---------+----------+-------+
|     883 |      876 |     1 |
|     856 |      883 |     1 |
|     859 |      883 |     1 |
|     860 |      883 |     1 |
|     883 |      879 |     1 |
|     883 |      880 |     1 |
|     883 |      881 |     2 |
+---------+----------+-------+
7 rows in set (0.00 sec)

and then discard 883 in the code. but how to get the query result in one column?

I don't know what title to give this question.

Answer:

The UNION construct is perfect for such tasks. A request using it can look like this:

SELECT sl_frend AS frend_id FROM frends WHERE m_frend = 883
    UNION SELECT m_frend AS frend_id FROM frends WHERE sl_frend = 883;

And here is the SQL Fiddle with a working example .

Scroll to Top