2013-08-05 177 views
0

我有2個表:Member和Member_Card。 Member_Card有鏈接到會員ID列列,因此部件具有一對多的關係,以Member_CardMySQL連接表WHERE子句

我輸出JSON如:

{ 
    "Name" : "Member Name", 
    "Cards": [ 
      { "Card_No" : "1234"}, 
      { "Card_No" : "4321"} 
     ] 
} 

會員及Member_Card有LastModifiedDate列。

我的查詢是這樣的:

SELECT Name FROM Member 
LEFT JOIN Member_Card 
    ON Member_Card.Member = Member.id 
WHERE Member.LastModifiedDate >= sinceDate 
    OR Member_Card.LastModifiedDate >= sinceDate 

與此查詢的問題是,它只會返回卡因爲sinceDate /會員修改(即,如果一個成員有2個卡和一個被修改AFER sinceDate,它將只返回1張卡)。我想返回成員及其所有卡片,不管卡片或成員本身是否在sinceDate後被修改。

我該如何查詢?或者我需要運行2個查詢?

回答

0
SELECT member.*,c.* 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 c on c.member=a.mid 
+0

感謝隊友,我有困難的時候用查詢^^ U – momo

+0

可以請你再次幫忙嗎?還有的情況下,一個成員沒有卡,如果日期匹配,我應該返回成員http://stackoverflow.com/questions/18123218/mysql-left-join-query-with-where-clause – momo