我有一个问题:我正在创建一个应该从3个表中获取数据的mysql视图,除了它不是3个表实际上是2但我需要两次相同的表。我认为所有的烹饪都是这样的:
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`@`localhost`
SQL SECURITY DEFINER
VIEW `ointeriorprecisadisto.com`.`new_view` AS
SELECT
`a`.`ad_title` AS `ad_title`,
`a`.`ad_details` AS `ad_details`,
`b1`.`category_name` AS `ad_category_id`,
`b2`.`category_name` AS `ad_category_parent_id`
FROM
((`ointeriorprecisadisto.com`.`wp_awpcp_ads` `a`
JOIN `ointeriorprecisadisto.com`.`wp_awpcp_categories` `b1`)
JOIN `ointeriorprecisadisto.com`.`wp_awpcp_categories` `b2`)
WHERE
((`a`.`ad_category_id` = `b1`.`category_id`)
AND (`a`.`ad_category_parent_id` = `b2`.`category_parent_id`))
只有一个问题,当我在此视图上运行查询时,它会返回每条记录的重复内容,例如:
title | details | cat_id | parent_ id
-------------------------------------
record 1 | record 1 | record 1 | record 1
record 1 | record 1 | record 1 | *record that shouldnt be here*
record 1 | record 1 | record 1 | *another one*
record 1 | record 1 | record 1 | *and another one*
基本上,它在最后一列上做笛卡尔积,对于"母表"中的每个记录,它为子表上的每一行创建记录
答案 0 :(得分:1)
试试这个:
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`@`localhost`
SQL SECURITY DEFINER
VIEW `ointeriorprecisadisto.com`.`new_view` AS
SELECT
`a`.`ad_title` AS `ad_title`,
`a`.`ad_details` AS `ad_details`,
`b1`.`category_name` AS `ad_category_id`,
`b1`.`category_name` AS `ad_category_parent_id`
FROM `ointeriorprecisadisto.com`.`wp_awpcp_ads` `a`
INNER JOIN `ointeriorprecisadisto.com`.`wp_awpcp_categories` `b1`
ON `a`.`ad_category_id` = `b1`.`category_id`
AND `a`.`ad_category_parent_id` = `b1`.`category_parent_id`;
答案 1 :(得分:1)
我认为这就是你想要的:
CREATE VIEW ointeriorprecisadisto.com.new_view AS
SELECT a.ad_title, a.ad_details,
c.category_name AS ad_category_id,
p.category_name AS ad_category_parent_id
FROM ointeriorprecisadisto.com.wp_awpcp_ads a LEFT JOIN
ointeriorprecisadisto.com.wp_awpcp_categories c
ON a.ad_category_id = c.ad_category_id LEFT JOIN
ointeriorprecisadisto.com.wp_awpcp_categories p
ON a.ad_category_parent_id = p.category_id
--------------------------------------^
我认为问题在于您在两个地方定义了父级。这似乎是一个糟糕的设计 - 父母应该在类别表或广告表中。我不确定你的意图;这使用了广告中的父级。
一些注意事项:
LEFT JOIN
,以防某些类别丢失。a.ad_title as ad_title
是多余的。