[英]How to SELECT FROM two tables and match two columns in SQL?
所以我想做的是從具有特定項目編號的table1中選擇所有記錄。 然后,我將聯接另一個表並僅獲得一個名為“ FloorId”的列,該列等於table1中的Project AND Element。
(SELECT Project FROM dbo.IMP_MODEL_GEOMETRY WHERE dbo.IMP_GEOMETRY.Project = dbo.IMP_ELEMENT.Project AND dbo.IMP_GEOMETRY.Element = dbo.IMP_ELEMENT.Element)
在dbo.IMP_GEOMETRY表中,我將在Project和Element上獲得多個結果,因此maby我可以選擇第一個。
這是我嘗試過的:
$sql = "SELECT * FROM dbo.IMP_ELEMENT WHERE Project LIKE '%$objNr%'
INNER JOIN dbo.IMP_MODEL_GEOMETRY ON dbo.IMP_ELEMENT.Project = dbo.IMP_MODEL_GEOMETRY.Project";
我是SQL的新手,並不真正知道“。”是什么。 在“ dbo.IMP”中代表。 表名是:dbo.IMP_ELEMENT(我看到查詢在點標記表的地方,而點后面是列名。但是在這種情況下,點既不代表表又代表列,它只是表中的一個點名稱。
除了JOIN(其中Project是列)(dbo.IMP_MODEL_GEOMETRY.Project)
我期望的表如下所示:
id Project Element FloorId
其中FloorId來自table2。
編輯
這兩個表都包含“項目”和“元素”,因此,我可以使用它們進行匹配。 在表1中,每個項目元素只有一行,但是在表2中,項目元素可以有多行,因此從表2中可以選擇僅找到找到的第一個匹配項。
您可以嘗試以下方式-
SELECT a.id,a.project,a.element,b.floorid FROM dbo.IMP_ELEMENT a
INNER JOIN dbo.IMP_MODEL_GEOMETRY b ON a.Project = b.Project and a.element=b.element
WHERE a.Project LIKE '%$objNr%'
我是SQL的新手,並不真正知道“。”是什么。 在“ dbo.IMP”中代表。
“。” 是識別所要元素的語法的一部分。 完全是..例如Adventureworks.dbo.customer
通過添加另一個“”,這也擴展到了列。 並指定列名稱。
但是開發人員很懶,如果您不指定數據庫,那么引擎將使用查詢當前連接到的數據庫。 不指定數據庫是完全正常的。
實際上,我們真的很懶,大多數人都不指定架構(dbo。部分),因為數據庫引擎只會檢查所有架構。
選擇數據-聯接
SELECT
--use table aliases (t1.) for each column, this is shorthand for dbo.table1
--if the same column exists in more than one table the database engine knows
--which one you want by looking at the aliases
t1.column_name
,t2.column_name
FROM
dbo.table1 as t1
INNER JOIN dbo.table2 as t2
--inner join returns only rows where the join matches both tables
ON t1.primary_key_column = t2.foreign_key_column
WHERE
--the join gives you a super table with all the rows that matched the join
--now you can add in any filters to your results
t1.some_column = 'foo'
;
或者您可以嘗試以下方法,
select table1.*, table2.FloorId
from IMP_ELEMENT as table1,
IMP_MODEL_GEOMETRY as table2
where table1.Project = table2.Project
and table1.Project like '%Whatever%';
您可以根據需要更改郵件表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.