简体   繁体   English

使用一个 SQL 查询的结果从另一个表中查找结果?

[英]Using result of one SQL query to find the result from another table?

I have two tables: Con and CFSK Both tables have a common column: ConID我有两个表:Con 和 CFSK 两个表都有一个公共列:ConID

Con has the following columns (atleast the ones I care about: ConID, Firstname, Lastname, SSN, DOB, HDate) CFSK has the following columns: Keyval, ConID, SystemID, Active, StChDt Con 具有以下列(至少我关心的那些:ConID、Firstname、Lastname、SSN、DOB、HDate) CFSK 具有以下列:Keyval、ConID、SystemID、Active、StChDt

Usually I do this:通常我这样做:

SELECT * 
  FROM Con
 WHERE Firstname = 'Jon' 
   and Lastname = 'Snow'

After I run this, I copy the value for ConID (let's say it is 99999) then run it against the CFSK table:运行此程序后,我复制 ConID 的值(假设它是 99999),然后针对 CFSK 表运行它:

SELECT * 
  FROM CFSK
 WHERE ConID IN (99999)

I would like to have a SQL script which consolidates both of these commands.我想要一个合并这两个命令的 SQL 脚本。

So let's say for example, I want to find what entries Arya Stark has in the CFSK table.例如,假设我想查找 Arya Stark 在 CFSK 表中的条目。 I would like a script where the user has to enter only the Firstname, Lastname and it shows the columns for BOTH tables that I have mentioned above.我想要一个脚本,用户只需输入名字、姓氏,它会显示我上面提到的两个表的列。

Any idea?任何想法? Sorry I'm a noob in SQL, tried a couple noobie tricks, none worked.抱歉,我是 SQL 的菜鸟,尝试了一些菜鸟技巧,但都没有奏效。 :( Any help would be greatly appreciated. :( 任何帮助将不胜感激。

THANK YOU GUYS FOR YOUR KIND ANSWERS, Solved my problem: all of them are good answers!谢谢你们的友好回答,解决了我的问题:所有这些都是很好的答案! :) You guys are beautiful! :) 你们很漂亮!

You join the two tables together:您将两个表连接在一起:

SELECT Con.*, CFSK.*
FROM Con 
JOIN CFSK ON Con.ConID = CFSK.ConID
WHERE
    FirstName = 'Jon'
AND LastName = 'Snow'

Use subquery使用子查询

SELECT * FROM CFSK WHERE ConID in 

(SELECT ConID FROM Con WHERE Firstname = 'Jon' and Lastname = 'Snow')

IN or EXIESTS is a typically approach: INEXIESTS是一种典型的方法:

SELECT *
FROM CFSK
WHERE EXISTS (SELECT 1
              FROM CON
              WHERE Con.Firstname = 'Jon' and CON.Lastname = 'Snow' AND
                    CFSK.ConID = CON.ConID
             );

Note: This assumes that the appropriate id for comparison is CON.ConID .注意:这假定用于比较的适当 id 是CON.ConID

I like this approach because it is suitable for an index on CON(ConID, FirrstName, LastName) .我喜欢这种方法,因为它适用于CON(ConID, FirrstName, LastName)上的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM