doushuhuai7247 2014-05-08 09:57
浏览 19
已采纳

SQL查询从另一个表中获取数据

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".

Practical case:

I have four tables: users, devices, preferences and user_devices.

  • Table users, there are user information and the user "ID".
  • Table devices, there are columns with device information, the device "ID" (device ID) and the device "key" (device internal ID).
  • Table preferences, "user ID" and some boolean fields with weekdays (monday, tuesday, wednesday...).
  • Table user_devices, assign ID (auto_increment, not important), "user_id" and "device_id" with relations to their respective tables. This tabble is used to assign a device to a user.

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.

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.

SELECT key FROM devices, user_devices WHERE devices.id = user_devices.device_id AND user_devices.user_id = 4

Thank you very much.

  • 写回答

2条回答 默认 最新

  • dongyi1111 2014-05-08 10:05
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制