我想列出mysql主表中的所有记录,只列出相关子表中的最后一条记录。这是代码。但它仅输出两个PK表的匹配记录。不列出主文件中的其余记录
SELECT contact.id, contact.title, contact.init, contact.first_name, contact.last_name, contact.city, contact.home_phone, contact.mobile_phone, contact.e_mail, status.status AS status, fundsource.fundsource AS fundsource, category.category AS category,contact.score, ROUND(value/1000000,1) AS value_M, jstate.jstate AS to_do, journal.l_date AS last_activity, journal.note AS journal FROM contact
LEFT JOIN journal ON journal.con_id=contact.id
LEFT JOIN jstate ON jstate.jstate_code=journal.jstate_code
LEFT JOIN category ON category.cat_code=contact.cat_code
LEFT JOIN status ON status.st_code=contact.st_code
LEFT JOIN fundsource ON fundsource.fundsource_code=contact.fundsource_code
WHERE journal.l_date=(SELECT MAX(journal.l_date) from journal WHERE journal.con_id = contact.id) GROUP BY contact.id
任何人都可以帮助我吗? PLS
答案 0 :(得分:0)
您遇到的问题是因为您已在LEFT JOIN表中的某个字段上设置了条件,因此您的WHERE子句基本上否定了LEFT JOIN。
LEFT JOIN说:"给我联系的所有内容,如果日记中有匹配的行,也请给我#34;
然后你添加了一些标准,"一旦你完成了这项工作,只给我一行,其中journal.l_date是最新的"。
这基本上排除了缺少journal.l_date的任何内容,从而过滤掉所有没有日记条目的联系人记录。
您需要为该记录引入该选项。
根据您使用的数据库,有两种方法可以执行此操作。
SELECT contact.id, contact.title, contact.init, contact.first_name,
contact.last_name, contact.city, contact.home_phone, contact.mobile_phone,
contact.e_mail, status.status AS status, fundsource.fundsource AS fundsource,
category.category AS category,contact.score, ROUND(value/1000000,1) AS value_M,
jstate.jstate AS to_do, journ.l_date AS last_activity, journ.note AS journal
FROM contact
LEFT JOIN
(SELECT * FROM journal
WHERE journal.l_date=(SELECT MAX(journal.l_date) from journal
WHERE journal.con_id = contact.id)
) as journ
LEFT JOIN jstate ON jstate.jstate_code=journ.jstate_code
LEFT JOIN category ON category.cat_code=contact.cat_code
LEFT JOIN status ON status.st_code=contact.st_code
LEFT JOIN fundsource ON fundsource.fundsource_code=contact.fundsource_code
GROUP BY contact.id
您可以看到我已将您的条件移动到左连接中的子选项中,并且我已将过滤后的表格替换为别名journ
(我已通过以下方式执行此操作因此,您可能需要通过对数据库运行来验证它。
这是我喜欢的方式。
有些数据库可能不喜欢这种语法。
`
SELECT contact.id, contact.title, contact.init, contact.first_name, contact.last_name, contact.city, contact.home_phone, contact.mobile_phone, contact.e_mail, status.status AS status, fundsource.fundsource AS fundsource, category.category AS category,contact.score, ROUND(value/1000000,1) AS value_M, jstate.jstate AS to_do, journal.l_date AS last_activity, journal.note AS journal FROM contact
LEFT JOIN journal ON journal.con_id=contact.id
LEFT JOIN jstate ON jstate.jstate_code=journal.jstate_code
LEFT JOIN category ON category.cat_code=contact.cat_code
LEFT JOIN status ON status.st_code=contact.st_code
LEFT JOIN fundsource ON fundsource.fundsource_code=contact.fundsource_code
WHERE (
(journal.con_id IS NULL)
OR ( journal.l_date=(SELECT MAX(journal.l_date) from journal WHERE journal.con_id = contact.id)
)
GROUP BY contact.id
`
根据您的数据库支持,您可能会对此选项感到更幸运。
这里我允许journal.con_id为NULL,作为一个有效的选项,它更好地匹配LEFT JOIN背后的基本思想。