一条语句中有两个选择语句 [英] Two select statements in a single statement
问题描述
我基本上有两个名为images
和users
的表. images
表具有以下字段:
I basically have two tables called images
and users
. The images
table has the following fields:
i_id | s_id | u_id | name | filename |
u_id
是users
表中的u_id
字段的外键,该字段具有以下字段:
u_id
is a foreign key to the u_id
field in the users
table, which has these fields:
u_id | username | password | email |
我正在运行这样的查询:
I'm running a query like this:
SELECT s_id, u_id, name, filename, filesize FROM images WHERE name = 'fYhWId'
这将返回用户的u_id
等.但是我想返回用户的用户名,而不是他们的u_id.因此,基本上,在该SELECT语句中,我还想运行:
This returns the u_id
of the user, among other things. But I want to return the users username, not their u_id. So basically, within that SELECT statement, I also want to run:
SELECT username FROM users WHERE u_id = 1
我可以为此使用两个查询,但是我试图减少我的应用程序运行的查询,而且我知道有一种方法可以将其组合成一个查询,但是我只是不知道:<
I could use two queries for this, but I'm trying to cut down on the queries my application runs, and I know there's a way to combine this into one query, but I just don't know it :<
有人知道答案吗?谢谢!
Does anyone know the answer? Thanks!
推荐答案
SELECT username FROM users WHERE u_id = (SELECT TOP 1 u_id FROM images WHERE name = 'fYhWId')
或
SELECT username FROM users WHERE u_id IN (SELECT u_id FROM images WHERE name = 'fYhWId')
或
SELECT username, s_id, images.u_id, name, filename, filesize
FROM images
INNER JOIN users on images.u_id = users.u_id
WHERE name = 'fYhWId'
这篇关于一条语句中有两个选择语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!