Ruby Sequel左外连接链式查询:添加时间条件失败求助
Hey there! Let's sort out that Sequel join condition problem you're facing. I totally get wanting to stick to chainable, idiomatic Sequel methods instead of falling back to raw Sequel.lit calls—it keeps your code cleaner and plays nicer with Sequel's query building system.
The Issue with Your Original Code
Your current query uses Sequel.lit for the col_2 comparison, which works, but you're right that we can replace it with Sequel's built-in expression API to keep everything chainable.
The Solution: Use Sequel's Expression Objects
Sequel lets you create column references and comparison conditions directly using its DSL, which integrates seamlessly with join clauses. Here's how to rewrite your query without raw SQL:
# Define your target time (can be a string or a Time/DateTime object) target_time = '2018-01-01 10:10:10' query.select_all(:table_1) .select_more(Sequel[:table_2][:col_1]) # Explicitly reference table_2 to avoid ambiguity .left_outer_join( :table_2, Sequel.and( table_1_id: :id, col_1: 1, Sequel[:table_2][:col_2] > target_time ) )
How This Works
Sequel[:table_2][:col_2]creates a safe, database-agnostic reference to thecol_2column intable_2.- Using the
>operator on this reference generates a proper comparison expression—Sequel handles all SQL escaping and formatting automatically (even if you pass aTime/DateTimeobject instead of a string, it'll convert it to the right format for your database). Sequel.andcombines all your join conditions into a single AND clause, just like your originallitapproach, but using pure Sequel methods.
Generated SQL
This query will produce exactly the kind of SQL you're expecting, something like:
SELECT `table_1`.*, `table_2`.`col_1` FROM `table_1` LEFT OUTER JOIN `table_2` ON (`table_2`.`table_1_id` = `table_1`.`id` AND `table_2`.`col_1` = 1 AND `table_2`.`col_2` > '2018-01-01 10:10:10')
Bonus Tip
If you're working with dynamic time values (like 1.week.ago), you don't need to convert them to strings manually—just pass the time object directly:
target_time = 1.week.ago # Same query structure as above
Sequel will handle converting the time object to a SQL-compatible timestamp based on your database adapter.
内容的提问来源于stack exchange,提问作者zombie_ghast

