Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如果两行在列中具有相同的值并且前五个字符相同,则筛选自联接查询_Sql_Database_Join_Sql Server 2012 - Fatal编程技术网

Sql 如果两行在列中具有相同的值并且前五个字符相同,则筛选自联接查询

Sql 如果两行在列中具有相同的值并且前五个字符相同,则筛选自联接查询,sql,database,join,sql-server-2012,Sql,Database,Join,Sql Server 2012,我使用self-join执行了以下查询 SELECT a.Product_ID , b.Parent_Product_ID, b.Product_Name FROM Product a, Product b where a.Product_ID = b.Parent_Product_ID 这就是结果 Product_ID Parent_Product_ID Prodcut_Name 311 311 Trench 353

我使用self-join执行了以下查询

SELECT 
    a.Product_ID , b.Parent_Product_ID, b.Product_Name 
    FROM Product a, Product b
    where a.Product_ID = b.Parent_Product_ID
这就是结果

Product_ID  Parent_Product_ID Prodcut_Name 
311        311             Trench
353        353             Blended wool
353        353             Blended wool polyester
355        355             Faux fur
357        357             Quilted 
358        358            Jackets-Polyester
359        359            Jackets-Wool
我试图通过以下方式过滤上述结果:

a) 如果两行在列中具有相同的值,则Product_ID=Parent_Prodcut_ID。 结果应该是这样的

353        353             Blended wool
353        353             Blended wool polyester
b) 如果产品名称中的前五个字符相同,则结果应为

353        353             Blended wool
353        353             Blended wool polyester
358        358            Jackets-Polyester
359        359            Jackets-Wool

只需将这些条件添加到
on
子句中(哦,您的查询也应该有这些条件):

第二点:

SELECT a.Product_ID , b.Parent_Product_ID, b.Product_Name 
FROM Product a JOIN
     Product b
     ON a.Product_ID = b.Parent_Product_ID AND
        LEFT(a.product_name, 5) = LEFT(b.product_name, 5);

如果您的数据库没有
LEFT()
函数,请改用
SUBSTR()
/
SUBSTRING()

您应该用正在使用的数据库标记您的问题。谢谢我现在标记
SELECT a.Product_ID , b.Parent_Product_ID, b.Product_Name 
FROM Product a JOIN
     Product b
     ON a.Product_ID = b.Parent_Product_ID AND
        LEFT(a.product_name, 5) = LEFT(b.product_name, 5);