MySQL-从2个不同的表和组结果中选择product_id

时间:2018-09-08 09:54:14

标签: mysql group-by

情况:

表1-#__ virtuemart_products

ggplot(data_small, aes(risk_datatheft_likelihood, risk_datatheft_damage)) + 
  geom_jitter(color="blue") + 
  labs(x = "damage", y = "likelihood",
       title = "Risk Map", subtitle = "Datatheft") + 
        theme_classic() +
        theme(legend.position="bottom") + 
        geom_hline(yintercept = 0.5, color="red") + 
        geom_hline(yintercept = 1.5) + 
        geom_hline(yintercept = 2.5) + 
        geom_hline(yintercept = 3.5) + 
        geom_hline(yintercept = 4.5) + 
        geom_vline(xintercept = 0.5, color="red") + 
        geom_vline(xintercept = 1.5) + 
        geom_vline(xintercept = 2.5) + 
        geom_vline(xintercept = 3.5) + 
        geom_vline(xintercept = 4.5)

data_big.csv
risk_datatheft_likelihood;risk_datatheft_damage
B;3
B;2
C;4
A;1
D;5

data_small.csv
risk_datatheft_likelihood;risk_datatheft_damage
C;4
A;2
B;3
C;4
D;1

表2-#__ virtuemart_product_badges

virtuemart_product_id | product_special
PRODUCTS_IDS | 0 or 1

我有一个默认的SQL

virtuemart_product_id | product_badge
PRODUCTS_IDS | for this situation code 3

结果是产品ID,例如2,3,225,...

我需要修改此SQL语法,以便从2个不同的表中选择ID,并返回一列。

如果我这样修改语法:

SELECT p.`virtuemart_product_id`
FROM `#__virtuemart_products` as p
WHERE p.`product_special` = 1;

结果是:

SELECT p.`virtuemart_product_id`, badges_table.`virtuemart_product_id`
FROM `#__virtuemart_products` as p, `#__virtuemart_product_badges` as badges_table
WHERE p.`product_special` = 1 OR badges_table.`badge` = 3
  1. 为什么第一列1,1,1,...?这里必须是product_id,没有product_special代码
  2. 我需要将此结果分组到一个字段tentmart_product_id

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找的是从两个不同表中获取的ID的UNION。

    SELECT p.`virtuemart_product_id`, badges_table.`virtuemart_product_id`
    FROM `#__virtuemart_products` as p, `#__virtuemart_product_badges` as 
    badges_table
    WHERE p.`product_special` = 1 OR badges_table.`badge` = 3

上面的查询在做什么,它正在两个表之间执行联接,条件是product_special应该为1或badge应该为3。因此,一个表的每一行将与另一表的每一行联接条件将满足的表。

要从两个表中获取ID,可以根据条件从每个表中获取结果,然后对它们执行UNION。例如

     (SELECT `virtuemart_product_id` FROM `#__virtuemart_products` WHERE 
     `product_special` = 1) 
      UNION 
     (SELECT `virtuemart_product_id` FROM 
     `#__virtuemart_product_badges` WHERE `badge` = 3)

我希望这会有所帮助。