繁体   English   中英

选择条件匹配单行的行?

[英]Selecting Rows Where Conditions Match A Single Row?

我有两个通过外键连接的表。 在表A中,我试图得到时间列中数据大于或等于表B起始列的所有行,以及时间列中的数据小于或等于表b结束列的位置。 我认为内部联接可能对此有用,但是,结果不是我所期望的。 它正在返回一些数据,但它们正在重复。

这是我有的:

SELECT * FROM columnA
INNER JOIN columnB
ON columnA.time >= columnB.start
OR columnA.time <= columnB.stop

我看错了吗? 内连接是否是收集此数据的正确方法?

更新:

实际上tableA的外键连接到tableB上的主键。 无论如何我这样做了:

SELECT * FROM tableA
INNER JOIN tableB
ON tableA.time >= tableB.start
AND tableA.time <= tableB.stop

我没有按照你所做的那样做的原因是因为数据已经存在于数据库中几年了,而我最近刚用外键添加了列。 因此该列中还没有任何数据。 这就是为什么我要查询它,以便我可以知道要用信息更新哪些列。 它将数据返回给我,但也返回了其他不符合要求的数据。

您必须使用定义其关系的columnName连接它们并将条件放在WHERE子句上。 不是ON条款

SELECT a.*, b.*
FROM    tableA a
        INNER JOIN tableB b
            ON a.colName = b.colName  -- colName is the column that links 
WHERE   a.`time` >= b.`start` OR      -- both tables.
        a.`time` <= b.`stop`

您需要使用外键进行连接,然后过滤掉与您的条件不符的结果。

Select * from TableA
Inner join TableB on TableA.Key = TableB.Key
Where TableA.time >= TableB.Start
Or TableA.time <= TableB.Stop

作为一项规则,我总是把W3Schools的SQL页面放在手边。 这是我可能忘记的SQL函数的最佳快速参考,需要快速复习。 也是一个学习的好地方。

SELECT a.* 
FROM columnA a 
INNER JOIN columnB b ON a.joiningColumn = b.joiningColumn
WHERE a.time >= b.start
OR a.time <= b.stop

从你的问题......

where the data in the time column is greater than or equal to the table B start column  
  AND  
where the data in the time column is less than or equal to the table b end column

但你的查询有......

columnA.time >= columnB.start  
  OR  
columnA.time <= columnB.stop  

结合其他人的说明,关于使用外键加入......

SELECT
  *
FROM
  TableA
INNER JOIN
  TableB
    ON  TableA.PK    = TableB.FK
    AND TableA.time >= TableB.start
    AND TableA.time <= TableB.stop 

我设法找出解决方案,添加一个WHERE来匹配我正在寻找的确切行中的数据。 这是我的解决方案:

SELECT * FROM tableA
INNER JOIN tableB
ON tableA.timetag >= tableB.start
AND tableA.timetag <= tableB.stop
WHERE tableB.id = "1"

暂无
暂无

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

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