简体   繁体   English

mySQL从两个匹配或不存在的表中选择

[英]mySQL Select from two tables where match or not exists

I have a problem setting up a SQL Query, hoping someone can help me. 我在设置SQL查询时遇到问题,希望有人可以帮助我。

So here's the task, I have two tables I would like to get with a single query. 所以这是任务,我想通过一个查询获得两个表。 Not a big problem, unless it comes to WHERE clause matching. 除非涉及WHERE子句匹配,否则这不是一个大问题。 I need all entries from Table A, but only matching entries from Table B, however keeping entries from Table A where the linked ID is not existing. 我需要表A中的所有条目,但只需要表B中的匹配条目,但是保留表A中不存在链接ID的条目。

To make clear what I have here is an example structure for the Tables... 为了弄清楚我在这里拥有的是表格的示例结构...

TABLE A    

ID | VAL1 | VAL2 | VAL3    
1  | abc  | xyz  | 123    
2  | abc  | xyz  | 123    
3  | abc  | xyz  | 123    
4  | abc  | xyz  | 123

TABLE B

ID | A-ID | X1 | X2 | X3 | FLAG    
1  | 1    | ab | xy | 98 | 1    
2  | 1    | ab | xy | 98 | 1    
3  | 1    | ab | xy | 98 | 0    
4  | 2    | ab | xy | 98 | 1    
5  | 2    | ab | xy | 98 | 0    
6  | 4    | ab | xy | 98 | 1

So if use this Query... 因此,如果使用此查询...

SELECT a.*, b.* FROM Table_A AS a LEFT JOIN Table_B AS b ON b.a-id = a.id WHERE b.flag = 0

... I get of course only the entries of A that have the matches in B, which would be ID 1 and 2 in this example, because 3 has no entry in B and 4 only an entry with FLAG 1. ...当然,我只得到在B中具有匹配项的A条目,在本示例中为ID 1和2,因为3在B中没有条目,而4在FLAG 1中只有条目。

However, in the Result-Array, I would need A3 and A4 as well, with the B Array-Values simply to be empty. 但是,在结果数组中,我也需要A3和A4,而B数组值只是为空。

I have currenlty no clue if this can be done easily and in a single Query. 我不知道是否可以通过单个查询轻松完成此操作。 I already tried a different approach by changing the query to something like... 我已经尝试过通过将查询更改为类似的方法...

SELECT a.*, (SELECT b.* FROM Table_B AS b WHERE b.a-id = a.id) AS array FROM Table_A AS a

... but in this case b.* is not allowed. ...但是在这种情况下,不允许b。*。 :( :(

Thanks Pat for your suggestion, I just found a solution that is working for me in this case, so for anyone who might be interested, I moved the WHERE clause to the ON clause and now I get the result I needed... 感谢Pat的建议,在这种情况下,我刚刚找到了一个对我有用的解决方案,因此对于任何有兴趣的人,我都将WHERE子句移到ON子句,现在我得到了所需的结果...

SELECT a.*, b.* FROM Table_A AS a LEFT JOIN Table_B AS b ON (b.a-id = a.id AND b.flag = 0)

Need to keep that in mind next time. 下次需要记住这一点。 :) :)

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

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