Mysql – 显示3个表的结果,不包括某些字段的NULL或EMPTY值
作者:互联网
我有3个简单的表,包含民意调查,用户和投票.我想通过干净的投票计数显示所有民意调查(有时候不会插入poll_id或user_id).
此外,我想显示一个投票的用户列表,类似于fb(现在我的解决方案是使用ajax调用获取的新查询来获取该列表.)
最好是创建一个查询来获取所有结果并从数组中单独读取它们,还是创建单独请求的最佳做法?
我的查询确实得到了有序列表,但包括空行或空行,对于包含> 10000结果的表来说非常慢.有什么建议?
SELECT id,
title,
pollid,
COUNT(pollid) AS clean_count
FROM
(
SELECT DISTINCT user_id, pollid
FROM tbl_votes
) AS tmp_tbl
JOIN tbl_polls
ON tbl_polls.id = tmp_tbl.pollid
WHERE not isnull(tmp_tbl.user_id)
GROUP BY pollid
ORDER BY clean_count DESC
与选民投票结果相符的代码:
SELECT DISTINCT fbid, COALESCE(username, 'User not found.')
AS username
FROM tbl_votes JOIN tbl_users
ON tbl_users.fbid = tbl_votes.user_id
WHERE pollid = $band_id AND not isnull(username)
解决方法:
试试这个:
SELECT id,
title,
pollid,
COUNT(pollid) AS clean_count,
group_concat(DISTINCT u.name) AS user
FROM
(
SELECT DISTINCT user_id, pollid
FROM tbl_votes
) AS tmp_tbl
JOIN tbl_polls
ON tbl_polls.id = tmp_tbl.pollid
JOIN tbl_users AS u
ON tmp_tbl.user_id = u.user_id
WHERE not isnull(tmp_tbl.user_id)
GROUP BY pollid
ORDER BY clean_count DESC
这是我使用的示例数据:
CREATE TABLE tbl_polls (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50)
);
CREATE TABLE tbl_users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE tbl_votes (
id INT AUTO_INCREMENT PRIMARY KEY,
pollid INT,
user_id INT,
INDEX (pollid,user_id),
FOREIGN KEY (pollid) REFERENCES tbl_polls(id),
FOREIGN KEY (user_id) REFERENCES tbl_users(user_id)
);
INSERT INTO tbl_polls (title)
VALUES ('Title 1'),('Title 2'),('Title 3');
INSERT INTO tbl_users (name)
VALUES ('Bob'),('Jack'),('Joe'),('Tom');
INSERT INTO tbl_votes (pollid,user_id)
VALUES (1,2),(1,2),(1,2),(1,3),(2,4),(2,1),(2,4),(2,4),(3,1),(2,1),(1,4);
我使用group concat来获取列表的名称.此外,为了加快数据库的速度,您是否尝试在外键中添加索引?
B.T.W.我不明白你的评论,有些投票缺乏pollid和user_id.如果是这样的话就看看这个.
标签:query-performance,php,mysql,optimization 来源: https://codeday.me/bug/20190806/1599040.html