简体   繁体   English

MySQL:在一个查询中从多个未连接的表中选择

[英]MySql: select from multiple not joined tables in one query

The following query works fine when all 3 tables have rows with status '1', but if one of the tables doesn't have a row with status '1' the entire query returns empty, even though other tables have rows with the requested status. 当所有3个表都具有状态为'1'的行时,以下查询可以正常工作,但是,如果其中一个表不具有状态为'1'的行,则即使其他表具有要求状态的行,整个查询也将返回空。

SELECT
table1.row_id as rowsone,
table2.row_id as rowstwo,
table3.row_id as rowsthree 

FROM
table1,
table2,
table3

WHERE table1.status = 1 AND table2.status = 1 AND table3.status = 1

I think that whats wrong with your file is that we all know that all the tables function separately but also all the table have an identical field name "status" right, the use of an AND condition is that all of the conditions must be met if one fails to satisfy the condition the whole of it would result to a false value or in your case 0, So what I would suggest is this: 我认为您的文件出了问题是,我们都知道所有表都单独起作用,而且所有表都具有相同的字段名“ status”,使用AND条件是必须满足所有条件,如果一个人不能满足条件,整个条件将导致一个错误的值,或者在您的情况下为0,所以我的建议是:

SELECT table1.row_id as rowsone, table2.row_id as rowstwo, table3.row_id as rowsthree SELECT table1.row_id作为rowsone,table2.row_id作为rowstwo,table3.row_id作为rowsree

FROM table1, table2, table3 从表1,表2,表3

WHERE status = 1 WHERE状态= 1

with this code it checks tables 1,2, and 3 if they have a status of one. 使用此代码,它将检查表1,2和3的状态是否为1。

As workarround if you know that there is just one row you may use subqueries 作为workarround,如果您知道只有一行,则可以使用子查询

SELECT ( SELECT title from table1 WHERE status =1),
       ( SELECT title from table2 WHERE status =1),
       ( SELECT title from table3 WHERE status =1)
 FROM DUAL;

If all the tables have a different number of records... you have to think about what kind of result you want. 如果所有表的记录数都不同,则...您必须考虑想要哪种结果。 May be something like a full outer join which is not supported in MySQL. 可能类似于MySQL不支持的完全外部联接。 It will be faster and more elegant to make several queries. 进行多个查询将更快,更优雅。

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

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