下面的代码在 MySQL Server 5.6 上进行了测试,
我希望/假设您的意图接近以下内容:
USE test;
CREATE TABLE users (
id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(80) NOT NULL);
CREATE TABLE pages (
id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(40) NOT NULL,
html VARCHAR(100) NOT NULL);
CREATE TABLE user_pages (
user_id INT UNSIGNED NOT NULL,
page_id INT UNSIGNED NOT NULL,
html VARCHAR(50) DEFAULT '',
PRIMARY KEY (user_id, page_id));
INSERT users (`name`) VALUES
('User 1'), ('User 2'), ('User 3');
INSERT pages (`name`, `html`) VALUES
('Welcome','Welcome to this page'),
('Goodbye','Thanks for visiting');
INSERT user_pages (user_id, page_id, html) VALUES
(1,1,"First user's welcome page"),
(1,2,"First user's goodbye page"),
(2,1,"Second user's welcome page");
SELECT DISTINCT
u.id AS `u_id`,
u.`name` AS `u_name`,
IFNULL(x.page_id, p.id) AS `p_id`,
IFNULL(p.`name`,'') AS `p_name`,
IFNULL(x.html,p.html) AS `p_html`
FROM users AS u
CROSS JOIN pages AS p
LEFT OUTER JOIN user_pages AS x
ON (x.user_id = u.id AND x.page_id = p.id);
上面的代码应返回每个用户的特定(如果存在)或一般页面。您还可以创建一个视图,并从中查询,就好像它是一个普通表一样:
CREATE OR REPLACE VIEW `user_page_details` AS
SELECT DISTINCT
u.id AS `u_id`,
u.`name` AS `u_name`,
IFNULL(x.page_id, p.id) AS `p_id`,
IFNULL(p.`name`,'') AS `p_name`,
IFNULL(x.html,p.html) AS `p_html`
FROM users AS u
CROSS JOIN pages AS p
LEFT OUTER JOIN user_pages AS x
ON (x.user_id = u.id AND x.page_id = p.id);
完成后,您的查询将非常简单:
SELECT * FROM user_page_details;
甚至
SELECT * FROM user_page_details WHERE u_id = 2;