3

表用户

id, name
1, Jay Bob
2, An Other

表格页

id, name, html
1, 'Welcome', 'Welcome to this page'
2, 'Goodbye', 'Thanks for visiting'

表 user_pages ** 存储用户特定版本的页面 **

user_id, page_id, html
1,        1,      'User id 1 Welcome page'

我基本上需要一个查询,它将返回以下数据集——即使没有数据存在,每种可能性都有一行。

数据集

user_id, page_id, html
1,        1,      'User is 1 Welcome page'
1,        2,      ''
2,        1,      ''
2,        2,      ''
4

3 回答 3

3

我认为最清晰的方法是使用子查询并cross join创建驱动程序表:

select driver.user_id, driver.page_id, up.html
from (select u.id as user_id, p.id as page_id
      from users u cross join
           pages p
     ) driver left outer join
     user_pages up
     on up.user_id = driver.user_id and up.page_id = driver.page_id;

重要的是子句中的user_idand来自驱动程序表而不是来自驱动程序表,因为后者可能是。page_idselectuser_pagesNULL

于 2013-04-08T17:54:41.737 回答
1

下面的代码在 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;
于 2013-04-08T18:44:09.907 回答
0

试试这个:

SELECT up.user_id, up.page_id, up.html
FROM users u,pages p
LEFT OUTER JOIN user_pages up ON u.id=up.user_id AND p.id=up.user_id
于 2013-04-08T17:51:19.873 回答