英文:
Select records which contains list of words from different table
问题
以下是[Product]表。
我想从[Product]中选择包含在Table_B中列出的单词的记录。
id | ProductName |
---|---|
1 | ABC代金券 |
2 | 维生素发生器 |
3 | 黑巧克力 |
4 | 快速充电 |
5 | 遥控器 |
6 | 电力发生器 |
7 | LED电视 |
以下是Table_B(其中包含一个单词列表)。
WordList |
---|
Generator |
Fast |
Controller |
所需输出:
Sr | Full_List |
---|---|
2 | 维生素发生器 |
4 | 快速充电 |
5 | 遥控器 |
6 | 电力发生器 |
为了方便,以下是示例数据的SQL代码:
DROP TABLE IF EXISTS #products
CREATE TABLE #products (
id INT NOT NULL PRIMARY KEY,
ProductName VARCHAR(255) NOT NULL
);
INSERT INTO #products (id, ProductName)
VALUES
(1, 'ABC代金券'),
(2, '维生素发生器'),
(3, '黑巧克力'),
(4, '快速充电'),
(5, '遥控器'),
(6, '电力发生器'),
(7, 'LED电视');
-
DROP TABLE IF EXISTS #Table_B
CREATE TABLE #Table_B (
WordList VARCHAR(255) NOT NULL
);
INSERT INTO #Table_B (WordList)
VALUES
('发生器'),
('快速'),
('遥控器');
像"or"的Where条件中使用Like运算符在我的情况下不起作用,因为列表是动态且很长。
<details>
<summary>英文:</summary>
Following is the [Product] Table.
I want to select records from [Product] that contain words listed in Table_B.
| id | ProductName |
|----|-------------------|
| 1 | ABC Voucher |
| 2 | Vitamin Generator |
| 3 | Dark Chocolate |
| 4 | Fast Charge |
| 5 | Remote Controller |
| 6 | Power Generator |
| 7 | LED TV |
Following is Table_B (Which contains a list of Words)
| WordList |
|------------|
| Generator |
| Fast |
| Controller |
**Required Output:**
| Sr | Full_List |
|----|-------------------|
| 2 | Vitamin Generator |
| 4 | Fast Charge |
| 5 | Remote Controller |
| 6 | Power Generator |
For easy, following is the SQL Code for sample data:
DROP TABLE IF EXISTS #products
CREATE TABLE #products (
id INT NOT NULL PRIMARY KEY,
ProductName VARCHAR(255) NOT NULL
);
INSERT INTO #products (id, ProductName)
VALUES
(1, 'ABC Voucher'),
(2, 'Vitamin Generator'),
(3, 'Dark Chocolate'),
(4, 'Fast Charge'),
(5, 'Remote Controller'),
(6, 'Power Generator'),
(7, 'LED TV');
-
DROP TABLE IF EXISTS #Table_B
CREATE TABLE #Table_B (
WordList VARCHAR(255) NOT NULL
);
INSERT INTO #Table_B (WordList)
VALUES
('Generator'),
('Fast'),
('Controller');
Like operator with "or" in Where condition will not work in my case as list is dynamic and long.
</details>
# 答案1
**得分**: 1
你可以将EXISTS与LIKE结合使用以实现你的需求。
```sql
SELECT * FROM #products p
WHERE EXISTS
(
SELECT * FROM #Table_B b
WHERE p.ProductName LIKE '%' + b.WordList + '%'
)
英文:
You can use EXISTS in combination with LIKE to achieve what you need.
SELECT * FROM #products p
WHERE EXISTS
(
SELECT * FROM #Table_B b
WHERE p.ProductName LIKE '%' + b.WordList + '%'
)
答案2
得分: -2
SELECT id, ProductName
FROM Product
WHERE ProductName IN
(SELECT WordList FROM Table_B)
英文:
SELECT id, ProductName
FROM Product
where ProductName IN
(SELECT WordList FROM Table_B)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论