这应该很容易,但由于某种原因,我和我的大脑今天不想合作。
我有一个包含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]
答案 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