这个SQL查询有什么问题吗?

时间:2013-08-22 06:51:45

标签: php mysql sql

Folowing是返回零行的查询,实际上它不应该:

SELECT distinct(usr.user_id)
FROM
    OCN.users AS usr,
    OCN.users_groups_subscribe AS usr_grp,
    OCN.tests_users AS test_usr
WHERE
    usr.user_id=usr_grp.subscribe_user_id AND
    usr.user_id=test_usr.test_user_user_id AND
    test_user_test_id=116 AND
    (usr.user_first_name LIKE '%ajay%' OR usr.user_last_name LIKE '%ajay%')
ORDER BY usr.user_first_name, usr.user_last_name

3 个答案:

答案 0 :(得分:4)

唯一可能的问题是test_user_test_id。我想根据你的其他专栏test_user.test_user_test_id来说它可能是test_user.test_user_user_id

尝试:

SELECT distinct(usr.user_id)
FROM
    OCN.users AS usr,
    OCN.users_groups_subscribe AS usr_grp,
    OCN.tests_users AS test_usr
WHERE
    usr.user_id=usr_grp.subscribe_user_id AND
    usr.user_id=test_usr.test_user_user_id AND
    test_usr.test_user_test_id=116 AND
    (usr.user_first_name LIKE '%ajay%' OR usr.user_last_name LIKE '%ajay%')
ORDER BY usr.user_first_name, usr.user_last_name

答案 1 :(得分:1)

首先,使用正确的ANSI连接语法:

SELECT distinct usr.user_id
FROM OCN.users AS usr
    inner join OCN.users_groups_subscribe AS usr_grp on usr_grp.subscribe_user_id = usr.user_id
    inner join OCN.tests_users AS test_usr on test_usr.test_user_user_id = usr.user_id
WHERE
    test_usr.test_user_test_id=116 AND
    (usr.user_first_name LIKE '%ajay%' OR usr.user_last_name LIKE '%ajay%')
ORDER BY usr.user_first_name, usr.user_last_name

现在尝试逐个注释你的连接(连同相应的列),看看为什么你没有得到任何行,比如

SELECT distinct usr.user_id
FROM OCN.users AS usr
    --inner join OCN.users_groups_subscribe AS usr_grp on usr_grp.subscribe_user_id = usr.user_id
    inner join OCN.tests_users AS test_usr on test_usr.test_user_user_id = usr.user_id
WHERE
    test_usr.test_user_test_id=116 AND
    (usr.user_first_name LIKE '%ajay%' OR usr.user_last_name LIKE '%ajay%')
ORDER BY usr.user_first_name, usr.user_last_name

答案 2 :(得分:0)

这为我带来了魔力:

SELECT distinct usr.user_id 
FROM OCN.users AS usr
    left join OCN.users_groups_subscribe AS usr_grp on usr_grp.subscribe_user_id = usr.user_id
    left join OCN.tests_users AS test_usr on test_usr.test_user_user_id = usr.user_id
WHERE
    test_usr.test_user_test_id=116 AND
    (usr.user_first_name LIKE '%pramod%' OR usr.user_last_name LIKE '%pramod%')
ORDER BY usr.user_first_name, usr.user_last_name