希望有人可以提供帮助,因为我很难理解如何正确查询
我有一个Member表和一个Member_Card表。 Member_Card有一个列成员,因此该卡与成员相关联。两个表都有一个LastModifiedDate列。会员可以没有,一张或多张卡。
我需要返回其LastModifiedDate> = sinceDate(指定日期)或其卡片(如果有)LastModifiedDate> = 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
}]
}]
第1名是匹配的LastModifiedDate没有卡的成员。第二个是具有不匹配的LastModifiedDate的成员,但他有2个关联的卡,其中一个具有匹配的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但后来却忽略了日期比较: - (
你能帮我解决这个问题吗?
答案 0 :(得分:3)
您希望将日期检查移动到内部查询的位置。
尝试类似:
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 )
)
答案 1 :(得分: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))
答案 2 :(得分: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'