2

希望有人可以提供帮助,因为我很难理解如何正确查询

我有一个 Member 表和一个 Member_Card 表。Member_Card 有一个成员列,因此卡片与成员相关联。两个表都有一个 LastModifiedDate 列。一个成员可以没有、一张或几张卡。

我需要返回 LastModifiedDate >= sinceDate(给定日期)或其卡(如果有)LastModifiedDate >= sinceDate 的所有成员。

想象 sinceDate 是 2013-01-01 00:00:00。我想输出这样的东西:

[{
    "Id": "001O000000FsAs7IAF",
    "LastModifiedDate": 2013-01-01 00:00:00,
    "Member_Card": null
}, {
    "Id": "001O000000FrpIXIAZ",
    "LastModifiedDate": 2012-12-12 00:00:00,

    "Member_Card": [{
        "Id": "a00O0000002w8FGIAY",
        "Member": "001O000000FhDSoIAN",
        "LastModifiedDate": 2013-01-01 00:00:00

    }, {
        "Id": "a00O0000002uYMtIAM",
        "Member": "001O000000FhDSoIAN",
        "LastModifiedDate": 2012-12-12 00:00:00
    }]
}, {
    "Id": "001O000000FsAg7IAF",
    "LastModifiedDate": 2013-01-01 00:00:00,
    "Member_Card": [{
        "Id": "a00O0000002w8FFIAY",
        "Member": "001O000000FhDSoIAN",
        "LastModifiedDate": 2012-12-12 00:00:00
    }]
}]

第一个是具有匹配 LastModifiedDate 且没有卡的成员。第二个成员的 LastModifiedDate 不匹配,但他关联了 2 张卡片,其中 1 张卡片具有匹配的 LastModifiedDate。第三个是与卡匹配的 LastModifiedDate 的成员。

多亏了所以我得到了以下查询:

SELECT member.*,card.* from member inner join (
SELECT distinct member.id as  mid FROM Member 
INNER JOIN Member_Card 
    ON Member_Card.Member = Member.id 
and ( Member.LastModifiedDate >= sinceDate  
    OR Member_Card.LastModifiedDate >= sinceDate ) ) a on a.mid=member.id
inner join member_card card on card.member=a.mid

哪个工作正常,但缺少会员没有任何关联卡的情况。

我试图将一些 INNER JOIN 更改为 LEFT JOIN,但随后它忽略了日期比较:-(

你能帮我解决这个问题吗?

4

3 回答 3

4

您想将日期检查移动到内部查询的位置。

尝试类似:

SELECT member.*,card.* 
FROM member 
LEFT JOIN member_card card on card.member=member.id
WHERE member.id IN (
    SELECT DISTINCT m.id FROM Member m
        LEFT JOIN Member_Card mc ON (mc.Member = m.id)
        WHERE ( m.LastModifiedDate >= sinceDate  
        OR mc.LastModifiedDate >= sinceDate ) 
)
于 2013-08-08T10:16:06.093 回答
0

试试这个...(尚待测试)

SELECT * FROM member m1
JOIN card c1 ON c1.member = m1.id
WHERE m1.id IN (
SELECT DISTINCT m.id from member m
JOIN card c ON c.member = m.id
WHERE (c.LastModifiedDate >=sinceDate  OR m.LastModifiedDate >= sinceDate))
于 2013-08-08T10:19:29.080 回答
0

你可以这样试试

SELECT o.status, o.date, c.name
FROM cliente c
LEFT JOIN orders o
ON c.id=o.id 
WHERE o.date = '2/1/2015'
于 2015-03-25T08:05:52.543 回答