MYSQL为具有相同值的行选择一次

时间:2016-09-02 04:40:42

标签: mysql

MYSQL

到目前为止,我的查询将从2个表中选择不同的column_names,并分别放在同一列下。

在表c的选择中,我想只为具有相同值的列选择一次。
示例:c_id有3行由值52组成,选择遇到的第一行但跳过其余行,对于值为41的行也是如此。

是否可以通过调整我当前的查询来实现,还是应该找到另一种方式?

 table m                    table c
 -----   -----  -----        -----   -----   -----
| m_id |m_date |m_siri|     | c_id | c_date| c_data|
 -----   -----  -----        -----   -----   -----
|   1  | 02-13 |  one |     |  52  | 01-12 |  xxx  |
 -----   -----  -----        -----   -----   -----
|   2  | 10-13 |  one |     |  41  | 11-13 |  yyy  |
 -----   -----  -----        -----   -----   -----
|   3  | 11-13 |  two |     |  41  | 12-13 |  zzz  |
 -----   -----  -----        -----   -----   -----
|   4  | 04-14 |  one |     |  52  | 08-14 |  eee  |
 -----   -----  -----        -----   -----   -----
|   5  | 01-15 |  two |     |  52  | 10-14 |  xxx  |
 -----   -----  -----        -----   -----   -----

(SELECT 
    m_ID AS id, m_date AS date 
FROM 
    m 
WHERE 
    m_siri='one' 
ORDER BY 
    m_date DESC LIMIT 2) 
UNION 
(SELECT 
    c_ID AS id, c_date AS date 
FROM 
    c 
ORDER BY 
    c_date DESC) 
ORDER BY date DESC

1 个答案:

答案 0 :(得分:0)

使用DISTINCT关键字仅从多个记录中获取一次记录。

(SELECT 
    m_ID AS id, m_date AS date 
FROM 
    m 
WHERE 
    m_siri='one' 
ORDER BY 
    m_date DESC LIMIT 2) 
UNION 
(SELECT 
    DISTINCT(c_ID) AS id, c_date AS date 
FROM 
    c 
ORDER BY 
    ch_date DESC) 
ORDER BY date DESC