我可以在临时 table 变量上使用 substring() 吗?

Can I use substring() on a temporary table variable?

我使用以下方法按每个域组的最高分对数据进行排序:

SELECT * from `Inputs` t 
order by (select max(`score`) from `Inputs` t1 where t1.`domain`=t.`domain`) desc, `score` desc

结果是:

query domain url score  
a www.google.com www.google.com/a  3  
a www.google.com www.google.com/b  1
a www.facebook.com www.google.com/c 2 

我不想将域和 url 一起存储在数据库中,而是想使用类似以下的方法将域计算为查询中 url 的函数:

SUBSTRING(`url` from 1 for locate('/',`url` ,10)-1) as `domain`

如果可能的话,我将能够使用更少的一列来实现相同的条目排序(如上所述):

query url score  
a www.google.com/a  3  
a www.google.com/b  1
a www.google.com/c 2 

如果可能的话,有人知道这是如何实现的吗?我还没有在 Whosebug 上找到关于对临时表使用列别名的其他问题。

我试过嵌套另一个查询,但没有成功:

SELECT *, SUBSTRING(`url` from 1 for locate('/',`url` ,10)-1) as `domain` from `Inputs` t
order by (select max(`score`), 
(select SUBSTRING(`url` from 1 for locate('/',`url` ,10)-1) as `domain` from `Inputs` t1 )
 from `Inputs` t1 where t1.`domain`=t.`domain`) asc, `score` asc

您可以使用 [substring_Index][1] 来达到这个目的,但您最终必须更改 CHAR 的数据类型或位置

实际上不需要该功能使代码更具可读性

架构(MySQL v5.7)

CREATE TABLE Inputs (
  `query` VARCHAR(1),
  `domain` VARCHAR(16),
  `url` VARCHAR(16),
  `score` INTEGER
);

INSERT INTO Inputs
  (`query`, `domain`, `url`, `score`)
VALUES
  ('a', 'www.google.com', 'www.google.com/a', '3'),
  ('a', 'www.google.com', 'www.google.com/b', '1'),
  ('a', 'www.facebook.com', 'www.google.com/c', '2');
  
CREATE FUNCTION geturl (_url CHAR(255))
       RETURNS CHAR(255) DETERMINISTIC
       RETURN SUBSTRING_INDEX(_url, "/", 1);

查询#1

select `query`, `domain`, `url` , `score`
from Inputs t
order by 
    (select max(score) from Inputs t1 where geturl(t1.url) = geturl(t.url)) desc,
    score desc;

| query | domain           | url              | score |
| ----- | ---------------- | ---------------- | ----- |
| a     | www.google.com   | www.google.com/a | 3     |
| a     | www.facebook.com | www.google.com/c | 2     |
| a     | www.google.com   | www.google.com/b | 1     |

View on DB Fiddle