MYSQL - 按首字母排序

时间:2012-02-28 15:53:33

标签: mysql

我有这个SQL查询(下面),它工作得很好但我需要修改它只选择带有$第一个字符的记录。我尝试了一些LIKE A%的变种而没有运气。我的情况的关键似乎是别名。如果我在ORDER之前使用WHERE名称LIKE'A%'我会收到错误。这似乎是合乎逻辑的地方。有什么建议吗?

SELECT  
  IF(company_name <> '', company_name, PC_last_name) AS name, 
  customer_id AS id, 
  company_name AS cn, 
  PC_first_name AS pcf, 
  PC_last_name AS pcl, 
  primary_phone 
FROM sales_customer 
ORDER BY name

3 个答案:

答案 0 :(得分:8)

试试这个,它是name的第一个字母。

SELECT IF(company_name <> '', company_name, PC_last_name) AS name, customer_id AS id, company_name AS cn, PC_first_name AS pcf, PC_last_name AS pcl, primary_phone
FROM sales_customer
ORDER BY SUBSTRING(name, 1, 1) ASC

答案 1 :(得分:3)

我认为您无法在WHERE上使用别名进行此比较。试试这个:

SELECT  
  IF(company_name <> '', company_name, PC_last_name) AS name, 
  customer_id AS id, 
  company_name AS cn, 
  PC_first_name AS pcf, 
  PC_last_name AS pcl, 
  primary_phone 
FROM sales_customer 
WHERE IF(company_name <> '', company_name, PC_last_name) LIKE 'A%'
ORDER BY name

答案 2 :(得分:2)

我在dba stackexchange上找到了这个: https://dba.stackexchange.com/questions/60137/mysql-is-it-possible-to-order-a-query-by-a-specific-letter-using-order-by

DROP TABLE IF EXISTS products;

create table products(pname CHAR(30),pdescription CHAR(30),price 
DECIMAL(10,2),manufacturer CHAR(30));

INSERT INTO products VALUES
('Toys','These are toys',15.25,'ABC'),
('Dolls','These are Dolls',35.25,'PQR'),
('DustPan','These are DustPan',75.25,'AZD'),
('Doors','These are Doors',175.25,'RAZD'),
('TV','These are TV',11175.25,'RAZD'),
('Bed','These are Bed',1175.25,'ARAZD');

/** Check all data **/

SELECT * FROM products;
+---------+-------------------+----------+--------------+
| pname   | pdescription      | price    | manufacturer |
+---------+-------------------+----------+--------------+
| Toys    | These are toys    |    15.25 | ABC          |
| Dolls   | These are Dolls   |    35.25 | PQR          |
| DustPan | These are DustPan |    75.25 | AZD          |
| Doors   | These are Doors   |   175.25 | RAZD         |
| TV      | These are TV      | 11175.25 | RAZD         |
| Bed     | These are Bed     |  1175.25 | ARAZD        |
+---------+-------------------+----------+--------------+
6 rows in set (0.00 sec)

/** Order by D% **/
SELECT 
        pname, pdescription, price
    FROM
    products
ORDER BY 
CASE
    WHEN pname LIKE 'D%' THEN 1
    ELSE 2
END;
+---------+-------------------+----------+
 | pname   | pdescription      | price    |
+---------+-------------------+----------+
| Dolls   | These are Dolls   |    35.25 |
| DustPan | These are DustPan |    75.25 |
| Doors   | These are Doors   |   175.25 |
| Toys    | These are toys    |    15.25 |
| TV      | These are TV      | 11175.25 |
| Bed     | These are Bed     |  1175.25 |
+---------+-------------------+----------+
6 rows in set (0.00 sec)