根据另一个表中的值获取所有值

时间:2014-05-07 07:40:34

标签: mysql join

这应该很容易,但由于某种原因,我和我的大脑今天不想合作。

我有一个包含sales列的表brick_region。砖块区域始终属于region。现在我想选择sales中属于我选择的特定砖块区域的所有值。我该怎么做?

SELECT *
FROM sales
JOIN brick_regions
ON (brick_regions.id = sales.brick_region)
WHERE sales.date BETWEEN '2014-01-01' AND '2014-03-30'
AND sales.brick_region = 2

但我希望最后一行是这样的:

AND brick_regions.region = [region ID of the brick region with ID 2]

3 个答案:

答案 0 :(得分:1)

也许尝试使用子查询?

SELECT * FROM sales 
LEFT JOIN brick_regions ON brick_regions.id = sales.brick_region 
WHERE sales.date BETWEEN '2014-01-01' AND '2014-03-30' 
AND brick_regions.region = (SELECT region FROM brick_regions WHERE id = 2); 

答案 1 :(得分:0)

问题的描述很难:) 因此,您希望根据日期从销售中获取一些行 从销售中获取具有所选行的相同brick_region的所有记录(按日期)?

如果是,那怎么样?

select * from sales where sales.brick_region IN(
select brick_region from sales WHERE 
WHERE sales.date BETWEEN '2014-01-01' AND '2014-03-30'
)

答案 2 :(得分:0)

  

砖块区域始终属于区域表

假设您有region表。所以这个查询可能是

SELECT *
FROM sales
JOIN brick_regions
ON (brick_regions.id = sales.brick_region)
JOIN region
ON (brick_regions.region = region.id)
WHERE sales.date BETWEEN '2014-01-01' AND '2014-03-30'
AND brick_regions.region = 2

OR

SELECT *
FROM sales
JOIN brick_regions
ON (brick_regions.id = sales.brick_region)
JOIN region
ON (brick_regions.region = region.id)
WHERE sales.date BETWEEN '2014-01-01' AND '2014-03-30'
AND region.id = 2