简体   繁体   中英

MySQL - distinct values from two columns

I have a table with multiple columns from which I need to get unique values from two of them.

The table looks something like this

msgid    sender    receiver  payload
1        service1  service2  xxx
2        service1  service3  xxx
3        service2  service3  xxx
...

The desired output should be: service1, service2, service3 (distinct values from columns sender and receiver)

I found many different approaches on how to do this and chose using UNION like this:

String query = "(SELECT sender AS service FROM messages) UNION " +
        "(SELECT receiver AS service FROM messages) ORDER BY service";

I tried also

String query = "(SELECT DISTINCT sender AS service FROM messages) UNION " +
        "(SELECT DISTINCT receiver AS service FROM messages) ORDER BY service";

which should produce the same since UNION already returns unique values. However, I am getting mysql exception:

java.sql.SQLException: Column 'sender' not found.

But column sender exists! When I run

String query = "SELECT DISTINCT sender FROM messages";

everything works just fine. Could you tell me, please, what am I doing wrong? I tried to use similar statement as this post suggested . Thanks!

EDIT: this is the EXACT query I am using right now:

String query = "SELECT sender AS service FROM messages UNION SELECT receiver AS service FROM messages ORDER BY service";

This query should work as mentioned in the comments. However, I still get the exception. Why so? Thanks for troubleshooting...

My mysql version is 5.6.

EDIT2: I had no idea that the problem could be with JDBC and not my statement. I apologiye for not providing this information in my question...

A guess in the dark is when you retrieve the data you use "sender" and not "service" that could explain why the first 2 queries work and the last doesn't.

Let me know if this is the case.

Assuming you are using JDBC :

    String query = "SELECT sender AS service FROM messages UNION SELECT receiver AS service FROM messages ORDER BY service";
    ResultSet rs = ps.executeQuery(query);
    while (rs.next()) {
        String value = rs.getString("sender"); // instead it should be "service"
        // Some other actions
    }

It should be this simple because UNION already removes duplicates

SELECT sender AS service FROM messages
UNION
SELECT receiver AS service FROM messages
ORDER BY service;

The MySQL docs for UNION agree with this and my sort here

Instead, provide a column alias in the first SELECT statement and refer to the alias in the ORDER BY

On SQLFiddle my query works http://sqlfiddle.com/#!2/c64e4/7 and does the OPs http://sqlfiddle.com/#!2/c64e4/8

只需从你的代码中删除"+"符号和"Distinct" ,然后尝试..

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