Mysql:在select中设置一个变量

时间:2009-04-27 15:46:16

标签: mysql

鉴于我的两个数据库表别名和订阅者都有这样的条目:

aliases.username    = '5551234567'  
aliases.contact     = 'sip:a_sip_username@sip.domain.com'  
subscriber.username = 'a_sip_username'  

我想在aliases.contact字段中只选择具有subscriber.username的匹配行。这是我的第一次尝试,但它没有返回任何内容:

SELECT
aliases.username as phone_number,
(@B:=subscriber.username) as user_name
FROM aliases,subscriber
WHERE aliases.contact regexp "^sip:@B[.*]"

这是否可行,还是应该将逻辑移到应用程序中?

1 个答案:

答案 0 :(得分:2)

SELECT  aliases.username AS phone_number,
        subscriber.username AS user_name
FROM    aliases, subscriber
WHERE   aliases.contact REGEXP CONCAT('^sip:', subscriber.user_name, '[.*]')

请注意,以下查询将更有效:

SELECT  aliases.username AS phone_number,
        subscriber.username AS user_name
FROM    aliases, subscriber
WHERE   aliases.contact LIKE CONCAT('sip:', subscriber.user_name, '%')

,这个虽然看起来很复杂,但效率更高:

CREATE FUNCTION fn_get_next_subscriber(initial VARCHAR(200)) RETURNS VARCHAR(200)
NOT DETERMINISTIC
READS SQL DATA
BEGIN
        DECLARE _username VARCHAR(200);
        DECLARE EXIT HANDLER FOR NOT FOUND RETURN UNHEX('FFFF');
        SELECT  username
        INTO    _username
        FROM    subscribers
        WHERE   username>= initial
                AND username NOT LIKE CONCAT(initial, '%')
        ORDER BY
                username
        LIMIT 1;
        RETURN _username;
END

SELECT  a.username AS phone_number,
        s.username AS user_name
FROM    (
        SELECT  si.*, CONCAT('sip:', username) AS fromcontact
        FROM    subscriber si
        ) s, aliases a
WHERE   a.contact >= fromcontact
        AND a.contact < fn_get_next_subscriber(fromcontact)

这将使用aliases (contact)上的索引并避免全表扫描。

在我的博客中查看此文章: