[英]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
使用 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.