这是我的疑问:
SELECT messages.id AS m_id, messages.user_id AS m_uid, messages.project_id AS m_pid, messages.date_created AS m_dc, messages.type AS m_type, messages.file_url AS m_fu, messages.message_text AS m_text, messages.deleted AS m_del,
projects.id AS p_id, projects.name AS p_name, projects.company_id AS p_cid,
users.id AS u_id, users.name AS u_name
FROM messages, projects, users
HAVING `m_pid` = '$project_id' AND m_uid = u_id
ORDER BY `m_dc` DESC
我一直在使用HAVING而不是WHERE,因为WHERE似乎没有使用我正在使用的AS关键字。结果是我的查询返回的结果超出了我的需要。我想我应该在这里使用JOIN,但我无法真正掌握它们。请帮忙!
:)谢谢
答案 0 :(得分:1)
这是真的,you should use JOIN instead of the FROM table1, table2 syntax。
更直接地回答您的问题:WHERE子句对表中的列进行操作 - HAVING子句对结果集(包括您的别名)进行操作。
您的表格如何相互关联?这是你需要首先回答的问题 - 一旦得到答案,你就把它直接放在JOIN的ON子句中。
SELECT messages.id AS m_id, messages.user_id AS m_uid, messages.project_id AS m_pid, messages.date_created AS m_dc, messages.type AS m_type, messages.file_url AS m_fu, messages.message_text AS m_text, messages.deleted AS m_del, projects.id AS p_id, projects.name AS p_name, projects.company_id AS p_cid,
users.id AS u_id, users.name AS u_name
FROM messages
JOIN users ON messages.user_id = user.id
JOIN projects ON projects.user_id = user.id # this is just a guess
WHERE messages.id = $project_id
ORDER BY `m_dc` DESC
为了更好地了解JOIN如何将表关联在一起,您可能希望查看这个方便的page showing JOINs as Venn diagrams。
答案 1 :(得分:0)
试试这个?
SELECT m.id AS m_id,
m.user_id AS m_uid,
m.project_id AS m_pid,
m.date_created AS m_dc,
m.type AS m_type,
m.file_url AS m_fu,
m.message_text AS m_text,
m.deleted AS m_del,
p.id AS p_id,
p.name AS p_name,
p.company_id AS p_cid,
u.id AS u_id,
u.name AS u_name
FROM messages as m
INNER JOIN projects as p on p.id = m.project_id
INNER JOIN users as u ON u.id = m.user_id
WHERE m.project_id = '$project_id'
ORDER BY ....
答案 2 :(得分:0)
SELECT
messages.id AS m_id, messages.user_id AS m_uid, messages.project_id AS m_pid,
messages.date_created AS m_dc, messages.type AS m_type, messages.file_url AS m_fu,
messages.message_text AS m_text, messages.deleted AS m_del,
projects.id AS p_id, projects.name AS p_name, projects.company_id AS p_cid,
users.id AS u_id, users.name AS u_name
FROM
messages
JOIN
users ON messages.user_id = users.id
JOIN
projects ON projects.id=messages.project_id
WHERE
`m_pid` = '$project_id'
ORDER BY
`m_dc` DESC