Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

MYSQL join condition match only one row based on priority


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
SELECT COALESCE(p2.id, p1.id) id, COALESCE(p2.post_title, p1.post_title) post_title
FROM wp_icl_translations t1
JOIN wp_posts p1 ON t1.element_id = p1.id
LEFT JOIN wp_icl_translations t2 ON t1.trid = t2.trid AND t2.language_code = 'fa'
LEFT JOIN wp_posts p2 ON t2.element_id = p2.id
WHERE t1.language_code = 'en'
ORDER BY id

fiddle


I want to use * somehow to get all columns that's really important .. both tables complete create in the fiddle here : https://dbfiddle.uk/?rdbms=mysql_5.6&fiddle=37f8af9fd14c60f4ea23fd4778b86806 – steve moretz

If you need complete columns then you must add one more tables copies and extract the whole rows from them. Primary key needed for such join:

SELECT p0.*, t0.*
FROM wp_icl_translations t1
JOIN wp_posts p1 ON t1.element_id = p1.id
LEFT JOIN wp_icl_translations t2 ON t1.trid = t2.trid AND t2.language_code = 'fa'
LEFT JOIN wp_posts p2 ON t2.element_id = p2.id
JOIN wp_icl_translations t0 ON t0.translation_id = COALESCE(t2.translation_id, t1.translation_id)
JOIN wp_posts p0 ON p0.id = COALESCE(p2.id, p1.id)
WHERE t1.language_code = 'en'
ORDER BY id

fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...