简体   繁体   English

SQL将属性与同一表中另一行的属性进行比较

[英]SQL compare attributes to another row's attribute in the same table

Let's say I have a table of people with their names and Dates of Birth. 假设我有一张桌子,上面有他们的名字和出生日期。 How can I select all people's names who have greater DofB than another person while only knowing that persons name and not DofB? 在仅知道某人的姓名而不知道DofB的情况下,如何选择所有DofB比其他人更大的人的名字?

You have some options, but I like a JOIN here. 您有一些选择,但是我喜欢这里的JOIN。

Assuming you have a unique name field (using a unique row identifier like id is probably better): 假设您有一个唯一的名称字段(使用像id这样的唯一行标识符可能更好):

SELECT p.name
  FROM person p
  JOIN person po
    ON po.name = :name_that_you_know
 WHERE p.dob > po.dob

This cross JOINs every person row with the row of the person that you named. 此交叉将每个人行与您指定的人行联接在一起。 The results are filtered by the date of birth comparison. 结果通过出生日期比较进行过滤。

Alternatively you can perform the filter in the JOIN condition: 或者,您可以在JOIN条件下执行过滤器:

SELECT p.name
  FROM person p
  JOIN person po
    ON po.name = :name_that_you_know
   AND po.dob < p.dob

Use a simple mysql query like 使用简单的mysql查询,例如

SELECT a.name, b.dob FROM table a INNER JOIN table b ON b.name = 'john' AND a.dob > b.dob

Something like that 像这样

This will find all people with a DOB greater (or younger) than the a person you are not sure of their DOB, but know their name: 这将发现所有拥有DOB的人比您不确定自己的DOB但知道他们的名字的人大(或更小)。

SELECT name
FROM yourTable
WHERE DOB > (SELECT DOB FROM yourTable WHERE name = 'nameyouknow'); 

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

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