简体   繁体   English

MySQL内部联接子查询

[英]MySQL inner join on subquery

I'm trying to construct an inner join on a subquery. 我正在尝试在子查询上构造内部联接。 I keep getting an error saying that it can't reopen table "t1". 我不断收到错误消息,说它无法重新打开表“ t1”。

This is what I'm trying to do in plain English: 这就是我要用简单的英语做的事情:

select all instances of "SystemHeader_Name" from "temp2" where "SystemHeader_Name" and "System_Value" are shared across "Tool_Name"

This is my attempt: 这是我的尝试:

SELECT t1.SystemHeader_Name FROM temp2 t1
INNER JOIN (
    SELECT DISTINCT Tool_Name, SystemHeader_Name, System_Value FROM temp2
) AS t2 ON (t2.SystemHeader_Name = t1.SystemHeader_Name 
    AND t2.System_Value = t1.System_Value);

How do I accomplish this? 我该如何完成?

Example
With: 附:

Tool_Name,SystemHeader_Name,System_Value
t1,h1,v1
t1,h2,v2
t2,h1,v1

The result should be: 结果应为:

h1

Issue 问题
After some more digging, I determined that my issue was with the temporary table. 经过更多的挖掘之后,我确定我的问题出在临时表上。 From this document: You cannot refer to a TEMPORARY table more than once in the same query. 这个文件: You cannot refer to a TEMPORARY table more than once in the same query.

It looks like I'll need to come up with a better method than using temporary tables. 看起来我需要比使用临时表提供更好的方法。 Thank you all for your help. 谢谢大家的帮助。

This should do it: 应该这样做:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

SELECT DISTINCT t1.SystemHeader_Name
FROM temp2 t1
JOIN temp2 t2
    ON t2.SystemHeader_Name = t1.SystemHeader_Name
    AND t2.System_Value = t1.System_Value
    AND t2.Tool_Name <> t1.Tool_Name

Try this: 尝试这个:

SELECT distinct t1.SystemHeader_Name
FROM temp2 t1
where exists(
    SELECT 'X'
    FROM temp2 t2
    WHERE t2.system_value = t1.system_value
    AND t2.tool_name <> t1.tool_name
    AND t2.systemheader_name = t1.systemheader_name
)

I use exists instead join because you don't want all rows but one if exists another systemheader 我使用exist而不是join,因为您不希望所有行,但如果一个行存在另一个systemheader

Tell me if accomplish your task. 告诉我是否完成任务。

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

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