MYSQL select query based on another tables entries

こ雲淡風輕ζ 提交于 2019-11-28 04:36:52

问题


I have stumped on this as I am a total beginner in MySql.

Here is a the basic of how the two tables are formed

Table 1 id,product_id, product_name

Table 2 id,product_id,active

Now i know how to do a select statement to query the results from one table but when I have to involve two, I am lost. Not sure if I have to use inner join, left join etc.

So how can I return the results of the product_id from table 1 only if in table 2 is active?


回答1:


It's pretty simple to join two tables:

select t1.* 
from Table1 t1
join Table2 t2 on t1.product_id = t2.product_id
where t2.active = 'Y'



回答2:


You could use JOIN (as Fosco pointed out), but you can do the same thing in the WHERE clause. I've noticed that it's a bit more intuitive method than JOIN especially for someone who's learning SQL. This query joins the two tables according to product_id and returns those products that are active. I'm assuming "active" is boolean type.

SELECT t1.*
FROM Table1 t1, Table2 t2
WHERE t1.product_id = t2.product_id AND t2.active = TRUE

W3Schools has a good basic level tutorial of different kinds of JOINs. See INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN.



来源:https://stackoverflow.com/questions/4176385/mysql-select-query-based-on-another-tables-entries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!