我的数据库中有多个表。假设表用户看起来像这样:
Users:
|id|name|gender|access|id_ext|
|1 | a | m | 1 | 32 |
|3 | b | m | 3 | 33 |
|4 | c | m | 1 | 34 |
|5 | d | f | 1 | 35 |
我想选择具有例如id_ext = 32
的用户,然后使用所选用户字段运行另一个select语句。
我可以通过首先让用户查询然后使用用户信息创建另一个查询来解决这个问题,但是必须有一种方法可以在同一个查询中执行此操作吗?
这是我现在使用的查询:
SELECT * FROM users NATURAL JOIN
(SELECT id FROM ages WHERE age BETWEEN
(SELECT limit_age_l FROM users WHERE id=17)
AND (SELECT limit_age_h FROM users WHERE id=17)) as a
WHERE NOT id = 17
AND locale = 'en_US'
AND limit_gender = 1
AND visible = 0
AND NOT EXISTS (SELECT view_id FROM matches WHERE user_id = 17 AND view_id = a.id)
LIMIT 1
问题是查询中的值id=17
,limit_gender=1
和locale = 'en_US'
未知。这些内容来自用户id_ext = '32'
。
答案 0 :(得分:3)
SELECT * FROM Users WHERE id in (SELECT id FROM Users WHERE id_ext='32');
答案 1 :(得分:2)
是 - 假设您的子查询格式为:
select field1, field2, ...
from Table1
join Table2 on ...
where ...
and Table1.id = N /* previously selected id from users */
然后使用第一个查询作为子查询:
select field1, field2, ...
from Table1
join Table2 on ...
where ...
and Table1.id = (select id from users where id_ext ='32')
/* replace = with IN if more than one id will be returned */
或者通过在后续查询中加入第一个查询的结果:
select field1, field2, ...
from users
join Table1 on Table1.id = users.id
join Table2 on ...
where ...
and users.id_ext ='32'
(请注意,这两种形式都假设用户尚未加入现有查询 - 如果是,只需将users.id_ext ='32'
条件添加到现有查询中。)
编辑:如果我已正确理解要求,则所需的查询可写为:
SELECT u.*
FROM users u
join ages a on u.id = a.id and
u.age between limit_age_l and limit_age_h
join users ul on ul.id = 17 and
ul.id <> u.id and
ul.locale = u.locale and
ul.limit_gender = u.limit_gender and
ul.visible = u.visible
AND NOT EXISTS (SELECT NULL
FROM matches m
WHERE m.user_id = ul.user_id AND m.view_id = a.id)
LIMIT 1
答案 2 :(得分:1)
SELECT * FROM users WHERE id = (SELECT id FROM users WHERE id_ext = '32');
答案 3 :(得分:-1)
Select * from users as user inner join userinfo as usinfo on usinfo.id=user.id_ext where user.id_ext='32'