0

我有一个包含人名和相应国家代码的 SQL 表。

----------------
 name    |  code
----------------
saket   |   IN

rohan   |   US

samules |   AR

Geeth   |   CH

Vikash  |   IN

Rahul   |   IN

Ganesh  |   US

Zorro   |   US

我想要的是,我应该能够按国家/地区分组code,名称以sa第一个开头,如果不是,那么Vi即使不是该组的最后一行。

当我尝试这个

SELECT * FROM MyTable GROUP BY code HAVING name like 'sa%' or name like 'vi%';

但是它给了我在有子句中与上述条件匹配的行。我希望如果条件失败然后给我该组的最后一行,这可能吗?如果可能,那怎么做?

4

2 回答 2

0

You can try this query. It returns what you need, but be aware - this query has two pitfalls:

  1. Subquery is a pain on 10^6 rows
  2. Field name in outer query is nonaggregated. MySQL documentation says that is is impossible to say what value will be selected for nonaggregated.

http://dev.mysql.com/doc/refman/5.7/en/group-by-extensions.html

select name, country 
from 
    (
    select *, if(name like 'sa%', 0, if(name like 'vi%', 2, 3) ) as name_order
    from tmp_names 
    order by country, name_order, name desc
) as tmp_names
group by country
order by name;

It returns

+---------+---------+
|  name   | country |
+---------+---------+
| Geeth   | CH      |
| saket   | IN      |
| samules | AR      |
| Zorro   | US      |
+---------+---------+
于 2013-10-01T14:36:47.770 回答
0

也许效率不高,但请尝试:

SELECT FIRST(`name`) AS `name`, `code` FROM (
    SELECT `name`, `code` FROM `MyTable`
        WHERE `name` LIKE 'sa%'
    UNION ALL
    SELECT `name`, `code` FROM `MyTable`
        WHERE `name` LIKE 'vi%'
    UNION ALL
    SELECT LAST(`name`) AS `name`, `code` FROM `MyTable` GROUP BY `code`
        HAVING `name` NOT LIKE 'sa%' AND `name` NOT LIKE `vi%'
) AS `a` GROUP BY `code`
于 2013-10-01T14:18:35.680 回答