简体   繁体   English

仅当该表中存在ID时才从表中选择mysql pdo php

[英]select from table only if the id exist in that table mysql pdo php

I want to create a select query using join on 3 or more tables. 我想使用3个或更多表上的联接创建一个选择查询。 I have 3 tables namely t1 , t2 , t3 and a common column id existing in all 3 tables. 我有3个表,即t1t2t3和所有3个表中都存在一个公共列id I want to select the 3 table if the id exists in the table my query is like this. 如果查询中存在ID,我想选择3表。

Select * from t1 
inner join t2 on t1.id = t2.id 
inner join t3 on t2.id = t3.id 
where t1.id = 1 and t2.id = 1 and t3.id = 1

the query is returning values if the id exists in all the 3 tables. 如果ID在所有3个表中都存在,则查询将返回值。 But if it is not in any table example t3 i will not return anything. 但是,如果在任何表示例t3中都没有,我将不会返回任何内容。 I am looking for a way that if it does not exist in t3 it should i proceed to just select from t1 and t2 我正在寻找一种方法,如果它在t3中不存在,我应该继续从t1t2进行选择

I think these sql wil helpful to you 我认为这些sql对您有帮助

Select * from t1,t2,t3 
where t1.id = 1 or t2.id = 1 0r t3.id = 1

these sql also will useful to you 这些SQL也将对您有用

SELECT * FROM t1 WHERE t1.id=1
UNION ALL
SELECT * FROM t2 WHERE t2.id=1
UNION ALL
SELECT * FROM t2 WHERE t2.id=1

Thank you. 谢谢。

Is this what you need? 这是您需要的吗?

SELECT * 
FROM t1 
INNER JOIN t2 on t1.id = t2.id 
LEFT JOIN  t3 on t2.id = t3.id 
WHERE t1.id = 1 AND t2.id = 1 AND (t3.id = NULL OR t3.id = 1)
SELECT * FROM t1 JOIN t2 ON t1.id = t2.id 
LEFT JOIN t2 ON t1.id= t2.id WHERE t1.id= 1

This will return null for t3 columns if id is not present in t3 这将返回空值t3列,如果id不存在于t3

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

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