Mysql 有没有办法按列值对结果排序?

Mysql 有没有办法按列值对结果排序?,mysql,sql,Mysql,Sql,我有很多列的MySQL表 id|Date |col1|col2|col3|col4|col5|... |col500| ----------------------------------------------------------------- 1|01.10.2019| 152| 99| 0|1598| 48| filled with zeros| 1| -------------------------------------

我有很多列的MySQL表

id|Date |col1|col2|col3|col4|col5|... |col500| ----------------------------------------------------------------- 1|01.10.2019| 152| 99| 0|1598| 48| filled with zeros| 1| ----------------------------------------------------------------- 2|02.10.2019| 12| 344| 19|2544| 3| filled with zeros| 152| ----------------------------------------------------------------- .... 有可能订一列吗

从表中选择*,其中日期为“2019年10月2日”,按列排序

得到这样的结果

id|Date |col4|col2|col500|col3|col1|col5|... | ----------------------------------------------------------------- 2|02.10.2019 |2544| 344| 152| 19| 12| 3|filled with zeros
CREATE TABLE tbl(
pk integer not null primary key default autoincrement,
id integer not null,
dt date not null,
xxx_id integer,
value integer);

如Madhur Bhaiya和p.Salmon所说,如果您想按列值排序,可能是因为您的表设计不正确,您可能在谈论行,而不是列。 而不是列ID/Date/col1/col2/…/col500,也许你需要一张这样的桌子

id|Date |col4|col2|col500|col3|col1|col5|... | ----------------------------------------------------------------- 2|02.10.2019 |2544| 344| 152| 19| 12| 3|filled with zeros
CREATE TABLE tbl(
pk integer not null primary key default autoincrement,
id integer not null,
dt date not null,
xxx_id integer,
value integer);
其中XXX_ID表示旧表中的列位置,可能是单个记录的标识符,我不知道您使用此表的目的是什么。 现在必须插入以下值:

INSERT INTO tbl (id, date, value) VALUES (1, '2019-10-01', 152);
INSERT INTO tbl (id, date, value) VALUES (1, '2019-10-01', 99);
INSERT INTO tbl (id, date, value) VALUES (1, '2019-10-01', 0);
INSERT INTO tbl (id, date, value) VALUES (1, '2019-10-01', 1592);
INSERT INTO tbl (id, date, value) VALUES (1, '2019-10-01', 48);
....
INSERT INTO tbl (id, date, value) VALUES (2, '2019-10-02', 12);
INSERT INTO tbl (id, date, value) VALUES (2, '2019-10-02', 344);
INSERT INTO tbl (id, date, value) VALUES (2, '2019-10-02', 19);
INSERT INTO tbl (id, date, value) VALUES (2, '2019-10-02', 2544);
...
你问题的答案变得很简单,比如

select * from tbl 
where id = 1 AND date = '2019-10-01'
order by value

最后一点:您可以决定使用零值插入记录,或跳过记录,或使用空值插入记录。这取决于表的目标。

否。结果集列是固定的。并在编译时,在读取数据之前决定。这有什么关系?列内的排序根本不重要,特别是当您将查询结果作为关联数组取出时。此外,当您有多个具有相似属性的列时,它就散发出一种非常糟糕的设计的味道。简短回答否。一个包含500多列的表-哦,天哪?它将在第二次插入时抛出错误,因为该表的主键为id。只需删除该列或为主键添加另一列即可key@James你是对的,我修改了答案。实际上,最好有一个主表,其中ID是主键,DATE是一个字段——在每个记录上重复DATE的值是错误的,表TBL中的字段ID应该作为该主表的外键引用。但我只写了一个简短的回答,我们不知道萨利赫·阿金要做什么。谢谢你的评论@Feacio,jarlh,Madhur Bhaiya,P.Salmon和James。该表的目的是计算从PLC可编程逻辑控制器读取的输入和输出I/O信号的每日重复次数。我有I/O信号的在线状态表,更新后触发,并在信号状态从0变为1时检查。然后在存档tbl中添加最后一个值的+1。简言之,我将按照您的建议准备归档表。向你问好。@SalihAKIN欢迎你。如果你喜欢,请接受答案