php mysql 查询3个表(用户、主题、消息)

标签 php mysql join

我需要列出包含所选用户和消息 ID 的结果主题,如下所示:

test 1 (topic)

message id (i will add a link for this ID)

(消息表中相同主题的同一用户可能有多个记录)

-------------------------------------
TABLES
-------------------------------------
TABLE:    users
id        int  (auto_increment)
user      varchar
-------------------------------------
TABLE:    topics
id        int
user_id   int  (index)
topic     varcahar
-------------------------------------
TABLE:    messages 
id        int  (auto_increment)
user_id   int  (index)
topic_id  int  (index)
message   text
-------------------------------------

我确实尝试了这段代码,但出现了错误。

SELECT users.id,users.user,topics.topic,messages.id FROM users,topics,messages WHERE messages.user_id=users.id and users.user='$_GET[user]' ORDER BY topics.topic

我该怎么做?

最佳答案

SELECT u.id, u.user, t.topic, m.id
FROM topics t
LEFT JOIN users u ON u.id = t.user_id
LEFT JOIN messages m ON m.user_id = u.id
WHERE u.user = 'xyz'
ORDER BY t.topic

但是你应该转义$_GET[user]

关于php mysql 查询3个表(用户、主题、消息),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21152901/

相关文章:

python - Pandas 中的 join 和 merge 有什么区别?

python - Pyspark 对列中列表中的值进行联接和操作

php - MySql缓存会导致性能问题吗?

mysql - 右加入不加入?

php - Foreach太慢

mysql - 何时在MySQL中使用单引号,双引号和反引号

mysql - 如何一次在所有数据库上运行 sql 命令?

MySQL:连接菜单表、用户表、访问表

php - SQL没有标识符,只有时间戳

php - Cron 作业未出现在 WP-Control 插件的 cron 列表中