简体   繁体   English

根据另一个表中的值从一个表中选择多个值

[英]Select multiple values from one table based on values in another

I'd like to select all the rows in the plot table where it exists in watchlist . 我想选择watchlist表中存在的plot表中的所有行。 For instance, with the example I've uploaded to SQLFiddle , I should be able to return rows 3 , 5 and 8 in plot with the query, because they exist in watchlist . 例如,用我上传的例子SQLFiddle ,我应该能够返回行358plot与查询,因为他们存在watchlist The problem is, I am not sure how to go about it. 问题是,我不确定该怎么做。 Any ideas? 有任何想法吗?

This is what I've done so far: 到目前为止,这是我所做的:

SELECT id, p_id, area, jobs from plot WHERE code="SA" AND p_id="3";

But only selects one row, but I understand that it would require a subquery of some sort ie replacing WHERE code="SA" AND p_id="3"; 但是只选择一行,但我知道这将需要某种子查询,即替换WHERE code="SA" AND p_id="3"; with a reference to the watchlist table. 并参考监视列表。

You can use INNER JOIN to check this: 您可以使用INNER JOIN进行检查:

SELECT t1.id
     , t1.p_id
     , t1.area
     , t1.jobs 
FROM plot t1 
JOIN watchlist t2 ON t1.p_id = t2.p_id 

SQLFiddle SQLFiddle

Returns ROWS 3, 5, and 8 返回ROWS 3、5和8

SELECT *
FROM plot, watchlist
WHERE plot.p_id = watchlist.p_id;

As you can see from the other responses - there are multiple solutions, so I will add a SUBQUERY solution since you mentioned subquery. 从其他响应中可以看到-有多个解决方案,因此既然您提到了子查询,我将添加一个SUBQUERY解决方案。

SELECT id, p_id, area, jobs 
  FROM plot 
  WHERE p_id in
  (SELECT p_id
      FROM watchlist);

try this it will work : 试试这个将工作:

SELECT t1.* from `plot` t1 JOIN `watchlist` t2 ON t1.`P_ID`=t2.`P_ID`

SQL Fiddle SQL小提琴

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

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