[英]SQL query to fetch data form another table
I've been trying to build a little complex SQL query to fetch some keys from a table which has no relation with the one in which I need to "ask". 我一直在尝试构建一个复杂的SQL查询来从表中获取一些与我需要“询问”无关的表。
Practical case: 实际案例:
I have four tables: users, devices, preferences and user_devices. 我有四个表:用户,设备,首选项和user_devices。
The thing is that I need to obtain all the "devices.key" of users that have the preference "monday" set to true in table preferences. 问题是我需要获取在表首选项中将首选项“monday”设置为true的所有“devices.key”用户。
Example: I ask the database for devices with preference monday true and I obtain an array with two device key. 示例:我向数据库询问具有首选项星期一的设备是否为真,我获得了一个带有两个设备密钥的数组。
This query fetch the device key of the user 4, but I need to fetch de device key of all the users with "monday" set to true (1) in the database. 该查询获取用户4的设备密钥,但是我需要在数据库中将“monday”设置为true(1)来获取所有用户的de device key。
SELECT key FROM devices, user_devices WHERE devices.id = user_devices.device_id AND user_devices.user_id = 4
Thank you very much. 非常感谢你。
you can try following query 你可以尝试以下查询
SELECT `devices`.`key`
FROM users
JOIN preferences ON users.id = preferences.user_id
JOIN user_devices ON users.id = user_devices.user_id
JOIN devices ON user_devices.device_id = devices.id
WHERE preferences.monday = true
obviously you'll have to check and correct the column names of preferences and users table in query to match your database column names. 显然,您必须检查并更正查询中的首选项和用户表的列名,以匹配您的数据库列名。
You can try this (i just hate JOINs ;p): 你可以尝试这个(我只是讨厌JOIN; p):
SELECT DISTINCT(`devices`.`key`)
FROM `devices`,`user_devices`,`preferences`
WHERE `devices`.`id` = `user_devices`.`device_id`
AND `preferences`.`user_id` = `user_devices`.`user_id`
AND `preferences`.`monday` = 1
Hope it would help 希望它会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.