簡體   English   中英

MySQL如何顯示兩個表中的數據

[英]MySQL how to display data from two tables

我正在嘗試顯示提交文章最多的人的用戶名,但我不知道如何使用MySQL和PHP進行操作,有人可以幫助我嗎?

這是MySQL代碼。

CREATE TABLE users (
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(255) DEFAULT NULL,
pass CHAR(40) NOT NULL,
PRIMARY KEY (user_id)
);

CREATE TABLE users_articles (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED mNOT NULL,
title TEXT NOT NULL,
acontent LONGTEXT NOT NULL,
PRIMARY KEY (id)
);

這是我到目前為止的代碼。

$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT COUNT(*) as coun, user_id 
                             FROM users_articles 
                             GROUP BY user_id 
                             ORDER BY coun DESC
                             LIMIT 1");

如果要獲取用戶名,則應使用下一個查詢:

SELECT users.name, COUNT(users_articles.id) AS coun 
FROM users_articles
LEFT JOIN users_articles ON users.id=users_articles.user_id
GROUP BY users_articles.user_id
ORDER BY coun DESC
LIMIT 1

SELECT COUNT(*) as coun, user_id , users.username SELECT COUNT(*) as coun, user_id , users.username
FROM users_articlesusers
WHERE users_articles.user_id = users.user_id
GROUP BY user_id
ORDER BY coun DESC
LIMIT 1

您想要做的是加入

您需要的SQL查詢是這樣的:

SELECT COUNT(*) as coun, users.user_id, username
FROM users_articles
INNER JOIN users
ON users_articles.user_id = users.user_id
GROUP BY user_id
ORDER BY coun DESC
LIMIT 1

我對此進行了測試,並且有效。
結果表包含用戶的文章數,用戶ID和用戶名。

從用戶中選擇u.user_id,count(ua.id)作為num_articles在u.user_id = ua.user_id上外部加入users_articles ua按u.user_id分組,按num_articles desc排序

左外部users_articles (而不是users_articles )確保所有用戶都在結果中表示,無論他們是否在users_articles都有記錄。

編輯:由於您只希望提交文章最多的人,所以您不一定需要左外部聯接(只要有至少一位撰寫任何文章的用戶)。 對於完整列表,這將很有用。

無論是上述怪胎給出的哪種查詢,您都只使用“不要忘記”選擇查詢中的“ 用戶名 ”字段,因為它們都不包含用戶名字段

這樣使用

SELECT COUNT(users_articles.*) as coun, users_articles.user_id, users.username 
FROM users_articles, users
WHERE users_articles.user_id = users.user_id
GROUP BY users.user_id
ORDER BY coun DESC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM