我想知道MySQL是否有可能通过包含名字和姓氏的名称列来命令我的结果。
例如:
“title”:Albert CATERSON - Barabara ABELS - Chris WASPINK
SQL ..
ORDER BY title
结果将是:
Albert CATERSON - Barabara ABELS - Chris WASPINK
但我想按姓氏排序我的结果:
ABELS Barabara - CATERSON Albert - WASPINK Chris
你知道在mysql中是否可以这样做?谢谢。
答案 0 :(得分:1)
试试这个
DROP TABLE IF EXISTS OrderBySurname;
Query OK, 0 rows affected, 1 warning (0.01 sec)
CREATE TABLE OrderBySurname(id INT, title VARCHAR(255));
Query OK, 0 rows affected (0.26 sec)
INSERT INTO `OrderBySurname` (`id`, `title`) VALUES ('1','Albert CATERSON'),('2', 'Barabara ABELS'),('3', 'Chris WASPINK');
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0
SELECT title , SUBSTRING_INDEX(title, ' ', -1) AS sur_name FROM OrderBySurname ORDER BY sur_name;
+-----------------+----------+
| title | sur_name |
+-----------------+----------+
| Barabara ABELS | ABELS |
| Albert CATERSON | CATERSON |
| Chris WASPINK | WASPINK |
+-----------------+----------+
3 rows in set (0.00 sec)
SELECT CONCAT(SUBSTRING_INDEX(title, ' ', -1),' ',SUBSTRING_INDEX(title, ' ', 1)) FROM OrderBySurname ORDER BY SUBSTRING_INDEX(title, ' ', -1);
+----------------------------------------------------------------------------+
| CONCAT(SUBSTRING_INDEX(title, ' ', -1),' ',SUBSTRING_INDEX(title, ' ', 1)) |
+----------------------------------------------------------------------------+
| ABELS Barabara |
| CATERSON Albert |
| WASPINK Chris |
+----------------------------------------------------------------------------+
3 rows in set (0.00 sec)
答案 1 :(得分:0)
如果您想通过姓氏订购,则需要使用SUBSTRING_INDEX
:
ORDER BY SUBSTRING_INDEX(title, ' ', -1);
但是,如果你想要姓氏首先出现,你需要这样的东西:
SELECT CONCAT(SUBSTRING_INDEX(title, ' ', -1), ' ', SUBSTRING_INDEX(title, ' ', 1))