简体   繁体   English

将一个表的查询结果与另一个表的默认值合并

[英]Combine query results from one table with the defaults from another

This is a dumbed down version of the real table data, so may look bit silly. 这是真实表数据的精简版,因此看起来有点傻。

Table 1 (users): 表1(用户):

id INT
username TEXT
favourite_food TEXT
food_pref_id INT

Table 2 (food_preferences): 表2(food_preferences):

id INT
food_type TEXT

The logic is as follows: 逻辑如下:

Let's say I have this in my food preference table: 假设我的食物偏好表中有这个:

1, 'VEGETARIAN'

and this in the users table: 在用户表中:

1, 'John', NULL, 1
2, 'Pete', 'Curry', 1

In which case John defaults to be a vegetarian, but Pete should show up as a person who enjoys curry. 在这种情况下,约翰默认是素食主义者,但皮特应该以喜欢咖喱的人身份出现。

Question, is there any way to combine the query into one select statement, so that it would get the default from the preferences table if the favourite_food column is NULL? 问题,是否有任何方法可以将查询合并为一个select语句,以便在favourite_food列为NULL时从首选项表中获取默认值?

I can obviously do this in application logic, but would be nice just to offload this to SQL, if possible. 我显然可以在应用程序逻辑中执行此操作,但如果可能的话,最好将其卸载到SQL。

DB is SQLite3... 数据库是SQLite3 ...

You could use COALESCE(X,Y,...) to select the first item that isn't NULL. 您可以使用COALESCE(X,Y,...)选择不为NULL的第一项。

If you combine this with an inner join , you should be able to do what you want. 如果将其与内部联接结合使用,则应该能够执行所需的操作。

It should go something like this: 它应该是这样的:

SELECT u.id AS id,
       u.username AS username,
       COALESCE(u.favorite_food, p.food_type) AS favorite_food,
       u.food_pref_id AS food_pref_id
FROM users AS u INNER JOIN food_preferences AS p
  ON u.food_pref_id = p.id

I don't have a SQLite database handy to test on, however, so the syntax might not be 100% correct, but it's the gist of it. 但是,我没有方便进行测试的SQLite数据库,因此语法可能不是100%正确的,但这是要点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM