很抱歉,如果这个问题看起来很奇怪,但我正在尝试在SQL中加入一些表,我无法做到正确。我是新手,所以,如果你想解释我做错了什么,我会非常感激。
基本上,我要做的是加入以下表格:会议,用户和服务。用户可以是主持人或管理员,并且该信息在设置列中定义。我希望INNER JOIN moderator_id与users.id WHERE users.settings ='主持人'还有INNER JOIN admin_id和users.id WHERE users.settings =' admin'。
希望你们明白我要做的事情:)
谢谢!
SELECT meetings.*
, users.id
, users.name
, users.settings
, services.id
, services.service_name
, services.price
FROM meetings
JOIN users
ON meetings.moderator_id = users.id
WHERE users.settings = 'moderator'
JOIN users
ON meetings.admin_id = users.id
WHERE users.settings = 'admin'
JOIN services
ON meetings.service_id = services.id
ORDER
BY meetings.date ASC
答案 0 :(得分:0)
SELECT meetings.*, users.id, users.name, users.settings, services.id, services.service_name, services.price
FROM meetings
INNER JOIN users as mods ON meetings.moderator_id = mods.id
INNER JOIN users as adms ON meetings.admin_id = adms.id
INNER JOIN services ON meetings.service_id = services.id
WHERE adms.users.settings = 'admin' AND mods.users.settings = 'moderator'
ORDER BY appointments.date ASC
我猜你需要为admins和moderatores指定用户实例,然后在连接后放置where。试试这个查询并告诉我它是否有效。
答案 1 :(得分:0)
SELECT的语法是:
SELECT <fields>
FROM <table>
JOIN <table> ON <condition>
JOIN <table> ON <condition>
...
WHERE <condition> AND <condition> AND ...
ORDER BY <column>, <column>, ...
即。列出所涉及的所有表,然后列出条件。这是SQL查询的一般结构,所以随意记住它:)。另请注意,这当然是极端简化,还有更多内容。 (例如,在WHERE子句中使用OR代替AND,但这是另一个故事。)祝你好运。
编辑:如果别名表,例如“FROM tablename AS newtablename”,则应使用别名newtablename作为WHERE中的条件,SELECT中的列等。否则,您将收到有关无法找到的内容的消息。您可以在查询期间重命名表,并抛弃旧名称。
答案 2 :(得分:0)
E.g:
SELECT m.*
, mods.name mod_name
, admins.name admin_name
, s.service_name
, s.price
FROM meetings m
JOIN users mods
ON mods.id = m.moderator_id
JOIN users admins
ON admins.id = m.admin_id
JOIN services s
ON s.id = m.service_id
WHERE mods.settings = 'moderator'
AND admins.settings = 'admin';
...或者,更有可能......
SELECT m.*
, mods.name mod_name
, admins.name admin_name
, s.service_name
, s.price
FROM meetings m
LEFT
JOIN users mods
ON mods.id = m.moderator_id
AND mods.settings = 'moderator'
LEFT
JOIN users admins
ON admins.id = m.admin_id
AND admins.settings = 'admin'
JOIN services s
ON s.id = m.service_id;
答案 3 :(得分:-1)
我通过结合你的一些建议找到了答案!它现在似乎工作得很好,所以谢谢你们的帮助!
SELECT meetings.*,
mods.id,
mods.name as mods_name,
mods.settings,
admins.id,
admins.name as admins_name,
admins.settings,
services.id,
services.service_name,
services.price
FROM meetings
INNER JOIN users as mods ON meetings.moderator_id = mods.id
INNER JOIN users as admins ON meetings.admin_id = admins.id
INNER JOIN services ON meetings.service_id = services.id
WHERE mods.settings = 'moderator' AND admins.settings = 'admin'
ORDER BY meetings.date ASC