簡體   English   中英

MySQL 查詢獲取數字最大的表名

[英]MySQL query to get table name with numerically highest number

我有一個 WordPress 多站點數據庫,其中有很多我需要刪除的孤立表。 名字的結構是這樣的。 表名中的數字是站點 ID。

wp_9892_wc_booking_relationships
wp_10001_wc_booking_relationships
wp_18992_wc_deposits_payment_plans
wp_20003_followup_coupons
wp_245633_followup_coupon_logs

我想查詢以從表名中找出最高的站點 ID。

我試過這樣的查詢

SELECT table_name FROM information_schema.tables
WHERE table_type = 'base table'
AND table_name REGEXP '^wp_[0-9]+_[a-z0-9]+'
ORDER BY table_name DESC
LIMIT 1; 

但這以一種意想不到的方式對結果進行排序:我得到

wp_9_woocommerce_log

當使用LIMIT 10時,我看到有更高數字的名稱:

wp_99_woocommerce_log
wp_999_woocommerce_log
wp_999_wc_webhooks
wp_999_wc_download_log
wp_999_wcpv_per_product_shipping_rules
wp_999_wcpv_commissions
wp_9999_wcpv_per_product_shipping_rules
wp_9999_wcpv_commissions
wp_9998_wc_points_rewards_user_points_log

這對 SQL 查詢可行嗎?

考慮以下數據示例。

CREATE TABLE test(
table_name  varchar(255) );

insert into test values
('wp_99_woocommerce_log'),
('wp_999_woocommerce_log'),
('wp_999_wc_webhooks'),
('wp_999_wc_download_log'),
('wp_999_wcpv_per_product_shipping_rules'),
('wp_999_wcpv_commissions'),
('wp_9999_wcpv_per_product_shipping_rules'),
('wp_9999_wcpv_commissions'),
('wp_9998_wc_points_rewards_user_points_log');

使用,

SELECT table_name 
FROM test
order by (substring_index(substring_index(table_name, 'wp_', -1), '_', 1) * 1 )  desc ;

將給出以下結果:

table_name
wp_9999_wcpv_per_product_shipping_rules
wp_9999_wcpv_commissions
wp_9998_wc_points_rewards_user_points_log
wp_999_woocommerce_log
wp_999_wc_webhooks
wp_999_wc_download_log
wp_999_wcpv_per_product_shipping_rules
wp_999_wcpv_commissions
wp_99_woocommerce_log

https://dbfiddle.uk/590L44Xr

使用 substring_index 兩次我們得到wp_和第二個_之間的數字。

* 1是將 varchar 轉換為 int 的快捷方式。

在你的情況下它會是這樣的

SELECT table_name 
FROM information_schema.tables
WHERE table_type = 'base table'
AND table_name REGEXP '^wp_[0-9]+_[a-z0-9]+'
ORDER BY  (substring_index(substring_index(table_name, 'wp_', -1), '_', 1) * 1 )   DESC
LIMIT 1; 

一種方法是提取數字並對其進行排序

例子

CREATE TABLE table1
    (`tb` varchar(34))
;
    
INSERT INTO table1
    (`tb`)
VALUES
    ('wp_9892_wc_booking_relationships'),
    ('wp_10001_wc_booking_relationships'),
    ('wp_18992_wc_deposits_payment_plans'),
    ('wp_20003_followup_coupons'),
    ('wp_245633_followup_coupon_logs')
;

 Records: 5 Duplicates: 0 Warnings: 0
SELECT tb FROM table1 ORDER BY REGEXP_SUBSTR(tb,"[0-9]+") + 0  DESC LIMIT 1
結核病
wp_245633_followup_coupon_logs

小提琴

所以你的查詢看起來像

SELECT table_name FROM information_schema.tables
WHERE table_type = 'base table'
AND table_name REGEXP '^wp_[0-9]+_[a-z0-9]+'
ORDER BY REGEXP_SUBSTR(table_name,"[0-9]+") + 0  DESC
LIMIT 1; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM