亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我可以在臨時表變量上使用 substring() 嗎?

我可以在臨時表變量上使用 substring() 嗎?

PHP
慕的地8271018 2023-09-08 21:46:59
我使用以下方法按每個域組的最高分對數據進行排序: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  1a 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  1a www.google.com/c 2 如果可能的話,有誰知道這是如何實現的?我還沒有在 stackoverflow 上找到有關對臨時表使用列別名的其他問題。我嘗試嵌套另一個查詢,但沒有運氣:SELECT *, SUBSTRING(`url` from 1 for locate('/',`url` ,10)-1) as `domain` from `Inputs` torder 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
查看完整描述

1 回答

?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

您可以使用 [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? ? ?|


查看完整回答
反對 回復 2023-09-08
  • 1 回答
  • 0 關注
  • 116 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號