简体   繁体   English

SQL查询以免费搜索另一个表中的名称

[英]SQL Query to find name from another table in free search

I have a table containing name of a specific object. 我有一个包含特定对象名称的表。 Let's say its columns are as following: id, other_id, name. 假设其列如下:id,other_id,名称。

Also I have another table which is connected to that previous table with the "other_id", so its columns are: other_id, name. 另外,我还有另一个表,该表使用“ other_id”连接到先前的表,因此其列为:other_id,名称。

To find a specific object in a regular search I have used: 为了在常规搜索中找到特定的对象,我使用了:

WHERE `name` LIKE '%$search%'"

and it is working fine. 而且工作正常。

However, I want to also search the name of the 2nd table. 但是,我也要搜索第二张表的名称。

So basically I have two tables, and an id that connects between them, and I want to be able to get the first table rows whose name like "search" or the 2nd table row that is connected to that specific row on the first table, also name is like "search". 所以基本上我有两个表,以及一个在两个表之间连接的ID,并且我希望能够获得名称如“ search”的第一表行或连接到第一表上该特定行的第二表行,也叫“搜索”。

Any ideas? 有任何想法吗?

You can join the tables on the ID that links them. 您可以在链接表的ID上加入表。 Then you can select any columns you want based on any criteria you specify. 然后,您可以根据指定的任何条件选择所需的任何列。

CREATE TABLE #TEST
(COL1 INT,
COL2 NVARCHAR(5))

CREATE TABLE #TEST2
(COL1 INT,
COL2 NVARCHAR(5))

INSERT INTO #TEST
VALUES ('1', 'BILL'), ('2', 'NANCY')

INSERT INTO #TEST2
VALUES ('1', 'RED'), ('2', 'BLUE')


SELECT A.COL2
      ,B.COL2
FROM #TEST A
JOIN #TEST2 B
ON A.COL1 = B.COL1
WHERE A.COL2 LIKE '%BILL%'

This example will select column 2 from both tables where table1.column1 is like '%Bill%'. 本示例将从两个表中选择第2列,其中table1.column1类似于'%Bill%'。

If you want results from both tables you can do: 如果要从两个表中获得结果,则可以执行以下操作:

SELECT id,other_id,name FROM TABLE1
WHERE `name` LIKE '%$search%'
UNION
SELECT null,other_id,name FROM TABLE2
WHERE `name` LIKE '%$search%'

As you only have other_id,name in your second table, the union will have null as id for the second table's results. 由于第二个表中只有other_id,name,因此联合的第二个表的结果的id将为null。

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

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