[英]hibernate- querying for rows, with distinct pair of values from two columns
[英]MySQL - distinct values from two columns
我有一個包含多列的表,我需要從中獲取其中兩列的唯一值。
該表看起來像這樣
msgid sender receiver payload
1 service1 service2 xxx
2 service1 service3 xxx
3 service2 service3 xxx
...
所需的輸出應該是: service1,service2,service3 (來自發送方和接收方列的不同值)
我找到了很多不同的方法來解決這個問題,並選擇使用UNION:
String query = "(SELECT sender AS service FROM messages) UNION " +
"(SELECT receiver AS service FROM messages) ORDER BY service";
我也試過了
String query = "(SELECT DISTINCT sender AS service FROM messages) UNION " +
"(SELECT DISTINCT receiver AS service FROM messages) ORDER BY service";
由於UNION已經返回唯一值,因此應該生成相同的值。 但是,我得到mysql異常:
java.sql.SQLException: Column 'sender' not found.
但是列發送者存在! 我跑的時候
String query = "SELECT DISTINCT sender FROM messages";
一切正常。 你能告訴我,我做錯了什么? 我試圖使用這篇文章建議的類似聲明。 謝謝!
編輯:這是我現在使用的EXACT查詢:
String query = "SELECT sender AS service FROM messages UNION SELECT receiver AS service FROM messages ORDER BY service";
此查詢應該如注釋中所述那樣工作。 但是,我仍然得到例外。 為什么這樣? 謝謝你排除故障......
我的mysql版本是5.6。
編輯2:我不知道問題可能是JDBC,而不是我的陳述。 我抱歉沒有在我的問題中提供這些信息......
黑暗中的猜測是當你檢索數據時,你使用“發送者”而不是“服務”,這可以解釋為什么前2個查詢有效,最后一個查詢沒有。
如果是這種情況,請告訴我。
假設您正在使用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
}
應該這么簡單,因為UNION已經刪除了重復項
SELECT sender AS service FROM messages
UNION
SELECT receiver AS service FROM messages
ORDER BY service;
而是在第一個SELECT語句中提供列別名,並引用ORDER BY中的別名
在SQLFiddle上我的查詢工作http://sqlfiddle.com/#!2/c64e4/7並執行操作系統http://sqlfiddle.com/#!2/c64e4/8
只需從你的代碼中刪除"+"
符號和"Distinct"
,然后嘗試..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.