首先,我想知道是否可以这样做?
以下是我的查询,我正在尝试使用条件构建。
SELECT CONCAT('record-', rl.record_id) AS tempId,
'sloka' AS type,
rl.record_id AS recordId,
rl.title AS title,
rl.locale as locale,
rl.intro AS intro,
rl.title AS localetitle,
NULL AS audioUrl,
lp.name AS byName,
lp.person_id AS byId,
lp.name AS onName,
lp.person_id AS onId
FROM record_locale rl
LEFT JOIN record r ON rl.record_id = r.record_id
LEFT JOIN locale_person lp ON r.written_on = lp.person_id
WHERE rl.title LIKE :title
AND rl.locale = :locale
AND lp.locale = :locale
UNION
SELECT CONCAT('lyric-', s.song_id) AS tempId,
'bhajan' AS type,
s.song_id AS recordId,
s.title,
l.locale as locale,
NULL AS intro,
l.title AS localetitle,
s.audio_url AS audioUrl,
lpb.name AS byName,
lpb.person_id AS byId,
lpo.name AS onName,
lpo.person_id AS onId
FROM song s
LEFT JOIN locale_person lpb
ON (s.written_by = lpb.person_id AND lpb.locale = :locale)
LEFT JOIN locale_person lpo
ON (s.written_on = lpo.person_id AND lpo.locale = lpb.locale)
INNER JOIN lyric l
ON (l.locale = lpb.locale AND l.song_id = s.song_id)
WHERE s.title LIKE :title AND s.approved_by IS NOT NULL
ORDER BY localeTitle ASC
// END
基于几个条件,我可能需要将两个查询联合起来,或者只需要单个查询而不需要联合。
答案 0 :(得分:1)
将SQL转换为JPQL通常是一个很好的第一步,因为我们不能完全告诉这些表映射到什么,或者你期望得到什么。如果可以在JPQL中执行,则应该可以使用条件查询。除了这种情况:JPA / JPQL没有union运算符,因此它不能直接在JPA中工作,但是一些提供程序(如EclipseLink)也有支持。参见:
UNION to JPA Query 和 http://www.eclipse.org/eclipselink/documentation/2.5/jpa/extensions/j_union.htm