我想有一个sql查询来获取文本列的结果顺序,其中id = 1或2或3。 同时保持id序列相同。 希望下面有任何帮助:
我的表:
id record text 1 1 Apple 2 1 Fruits 3 1 Nice 1 2 Mango 2 2 Fruits 3 2 Moderate 1 3 Car 2 3 Vehicles 3 3 Nice
按照id = 1
排序的预期结果id record text 1 1 Apple 2 1 Fruits 3 1 Nice 1 3 Car 2 3 Vehicles 3 3 Nice 1 2 Mango 2 2 Fruits 3 2 Moderate
或 如果按id = 2
排序,则为预期结果id record text 1 1 Apple 2 1 Fruits 3 1 Nice 1 2 Mango 2 2 Fruits 3 2 Moderate 1 3 Car 2 3 Vehicles 3 3 Nice
或 如果按id = 3
排序,则为预期结果id record text 1 2 Mango 2 2 Fruits 3 2 Moderate 1 1 Apple 2 1 Fruits 3 1 Nice 1 3 Car 2 3 Vehicles 3 3 Nice
答案 0 :(得分:1)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL
,record INT NOT NULL
,text VARCHAR(12) NOT NULL
,PRIMARY KEY(id,record)
);
INSERT INTO my_table VALUES
(1 ,1 ,'Apple'),
(2 ,1 ,'Fruits'),
(3 ,1 ,'Nice'),
(1 ,2 ,'Mango'),
(2 ,2 ,'Fruits'),
(3 ,2 ,'Moderate'),
(1 ,3 ,'Car'),
(2 ,3 ,'Vehicles'),
(3 ,3 ,'Nice');
SELECT * FROM my_table;
+----+--------+----------+
| id | record | text |
+----+--------+----------+
| 1 | 1 | Apple |
| 1 | 2 | Mango |
| 1 | 3 | Car |
| 2 | 1 | Fruits |
| 2 | 2 | Fruits |
| 2 | 3 | Vehicles |
| 3 | 1 | Nice |
| 3 | 2 | Moderate |
| 3 | 3 | Nice |
+----+--------+----------+
SELECT x.*
FROM my_table x
JOIN my_table y
ON y.record = x.record
AND y.id = 3
ORDER
BY y.text
, x.record
, x.id;
+----+--------+----------+
| id | record | text |
+----+--------+----------+
| 1 | 2 | Mango |
| 2 | 2 | Fruits |
| 3 | 2 | Moderate |
| 1 | 1 | Apple |
| 2 | 1 | Fruits |
| 3 | 1 | Nice |
| 1 | 3 | Car |
| 2 | 3 | Vehicles |
| 3 | 3 | Nice |
+----+--------+----------+